algo_input stringlengths 240 3.91k | solution_py stringlengths 10 6.72k | solution_java stringlengths 87 8.97k | solution_c stringlengths 10 7.38k | solution_js stringlengths 10 4.56k | title stringlengths 3 77 |
|---|---|---|---|---|---|
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
Example 1:
Input: s = "abccccdd"
Output: 7
Explanation: One longest ... | class Solution:
def longestPalindrome(self, s: str) -> int:
letters = {}
for letter in s: #count each letter and update letters dict
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
plus1 = 0 # if ... | class Solution {
public int longestPalindrome(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int evenNo = 0;
int oddNo = 0;
for ( int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
map.put(c, map... | class Solution {
public:
int longestPalindrome(string s) {
map<char,int> mp;
for(int i=0;i<s.length();i++){
mp[s[i]]++;
}
int ans = 0;
int odd = 0;
for(auto i:mp){
if(i.second % 2 == 1){
odd = 1;
}
ans = ... | var longestPalindrome = function(s) {
const hashMap = {};
let ouput = 0;
let hashOdd = false;
for (let i = 0; i < s.length; i++) {
if (!hashMap[s[i]]) {
hashMap[s[i]] = 0;
}
hashMap[s[i]] += 1;
}
Object.values(hashMap)?.forEach(character => {
ouput +... | Longest Palindrome |
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division ... | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
pre = [1]* (len(nums)+1)
back = [1]*(len(nums)+1)
for i in range(len(nums)):
pre[i+1] = pre[i]*nums[i]
for i in range(len(nums)-1,-1,-1):
back[i-1] = back[i]*nums[i]
for i in ... | class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int pre[] = new int[n];
int suff[] = new int[n];
pre[0] = 1;
suff[n - 1] = 1;
for(int i = 1; i < n; i++) {
pre[i] = pre[i - 1] * nums[i - 1];
}
for(... | class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int zero=0,product=1;
for(auto i:nums){
if(i==0)
zero++;
else product*=i;
}
for(int i=0;i<nums.size();i++){
if(nums[i] == 0 && zero>1){
nums... | /**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
let result = [];
let len = nums.length;
let prefix = 1;
for (let i = 0; i < len; i++) {
result[i] = prefix;
prefix *= nums[i];
}
let postfix = 1;
for (let i = len - 1; i >= 0; i--) {
result[i] *= ... | Product of Array Except Self |
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining el... | class Solution:
def maxEqualFreq(self, nums: List[int]) -> int:
ans = 0
n = len(nums)
countToFreq = defaultdict(int)
# key = count value = Freq ex 2 occured 3 times in nums so 2 : 3
freqToCount = defaultdict(int)
# key = freq value = count ex 2 numbers occured 3 time... | import java.util.TreeMap;
import java.util.NavigableMap;
class Solution {
public int maxEqualFreq(int[] nums) {
Map<Integer, Integer> F = new HashMap<>(); //Frequencies
NavigableMap<Integer, Integer> V = new TreeMap<>(); //Values for frequencies
int max = 0;
for (int i = 0; ... | class Solution {
public:
int maxEqualFreq(vector<int>& nums) {
int n=nums.size();
unordered_map<int,int> mp1,mp2; //one to store the frequency of each number , and one which will store the frequency of the frequency
int ans=0;
for(int i=0;i<n;i++)
{
int c=nums[i];... | // *NOTE: ternary operator is to handle if key is undefined since javascript doesn't have a default object value
var maxEqualFreq = function(nums) {
// create cache to count the frequency of each number
const numCnt = {};
// create cache to count the number of 'number of frequencies'
// e.g. [1,2,3,2,4,4,3,... | Maximum Equal Frequency |
Design a queue that supports push and pop operations in the front, middle, and back.
Implement the FrontMiddleBack class:
FrontMiddleBack() Initializes the queue.
void pushFront(int val) Adds val to the front of the queue.
void pushMiddle(int val) Adds val to the middle of the queue.
void pushBack(int val) Adds ... | class FrontMiddleBackQueue:
def __init__(self):
self.front = deque()
self.back = deque()
def _correct_size(self):
while len(self.back) > len(self.front):
self.front.append(self.back.popleft())
while len(self.front) > len(self.back) + 1:
self.back.append... | class FrontMiddleBackQueue {
Deque<Integer> dq1, dq2;
public FrontMiddleBackQueue() {
dq1 = new ArrayDeque<Integer>();
dq2 = new ArrayDeque<Integer>();
}
public void pushFront(int val) {
dq1.addFirst(val);
}
public void pushBack(int val) {
d... | class FrontMiddleBackQueue {
public:
deque<int> list1;
deque<int> list2;
int size;
FrontMiddleBackQueue() {
size = 0;
}
void pushFront(int val) {
if(list1.size()- list2.size() == 0)
{
list1.push_front(val);
}
else
... | // T.C:
// O(1) for init and methods other than pushMiddle(), popMiddle()
// O(N) for pushMiddle(), popMiddle()
// S.C: O(N) for storage
// Doubly linked list node
function ListNode(val, prev, next) {
this.val = val || 0;
this.prev = prev || null;
this.next = next || null;
}
var FrontMiddleBackQueue = f... | Design Front Middle Back Queue |
Given an integer array nums and an integer k, modify the array in the following way:
choose an index i and replace nums[i] with -nums[i].
You should apply this process exactly k times. You may choose the same index i multiple times.
Return the largest possible sum of the array after modifying it in this way.
&nb... | from heapq import heapify, heapreplace
class Solution:
def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
heapify(nums)
while k and nums[0] < 0:
heapreplace(nums, -nums[0])
k -= 1
if k % 2:
heapreplace(nums, -nums[0])
return sum(... | class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for(int val : nums) minHeap.add(val);
while(k > 0){
int curr = minHeap.poll();
minHeap.add(-curr);
k--;
}
... | class Solution {
public:
int largestSumAfterKNegations(vector<int>& A, int k) {
priority_queue<int, vector<int>, greater<int>> pq(A.begin(), A.end());
while(k--){
int t=pq.top();pq.pop();
pq.push(t*-1);
}
int n=0;
while(!pq.empty()){
int ... | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var largestSumAfterKNegations = function(nums, k) {
let negations = k
let index = 0
const sortedNums = [...nums]
// Sort in increasing order
sortedNums.sort((a, b) => a - b)
// loop into the sorted array using the
/... | Maximize Sum Of Array After K Negations |
You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.
Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.
Return the minimum possible difference.
... | class Solution:
def minimumDifference(self, nums: List[int], k: int) -> int:
nums.sort()
cur = float('inf')
for i in range(len(nums)-k+1):
cur = min(cur, nums[i+k-1]-nums[i]) | class Solution {
public int minimumDifference(int[] nums, int k) {
if(k == 1)return 0;
int i = 0,j = k-1,res = Integer.MAX_VALUE;
Arrays.sort(nums);
while(j < nums.length){
res = Math.min(res,nums[j] - nums[i]);
j++;
i++;
}
return... | class Solution {
public:
int minimumDifference(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int res = nums[k-1] - nums[0];
for (int i = k; i < nums.size(); i++) res = min(res, nums[i] - nums[i-k+1]);
return res;
}
}; | ```/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var minimumDifference = function(nums, k) {
nums.sort((a,b)=>a-b)
let min=nums[0],max=nums[k-1],diff=max-min
for(let i=k;i<nums.length;i++){
diff=Math.min(diff,nums[i]-nums[i-k+1])
}
return diff
};`` | Minimum Difference Between Highest and Lowest of K Scores |
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer num, return its complement.
Example 1:
Input: num = 5... | class Solution:
def findComplement(self, num: int) -> int:
i = 0
while(2**i <= num):
i += 1
return (2**i - num - 1) | class Solution {
public int findComplement(int num) {
int x=0;int sum=0;
while(num>0){
int i = num%2;
if(i==0){
sum+=Math.pow(2,x++);
}
else{
x++;
}
num/=2;
}
return sum;
}
} | class Solution {
public:
int findComplement(int num) {
long n=1;
while(n-1<num)
{
n<<=1;
}
n--;
return n-num;
}
}; | var findComplement = function(num) {
return num ^ parseInt(Array(num.toString(2).length).fill("1").join(""), 2)
} | Number Complement |
Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence.
If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with ... | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort(reverse=True)
val = sum(nums)
temp = []
for i in range(len(nums)):
temp.append(nums[i])
if sum(temp)>val-sum(temp):
return temp
| class Solution {
public List<Integer> minSubsequence(int[] nums) {
int total = 0;
for(int i=0;i<nums.length;i++){
total += nums[i];
}
Arrays.sort(nums);
int sum = 0;
ArrayList<Integer> ans = new ArrayList<>();
for(int i=nums.length-1;i>=0;i--){
... | class Solution {
public:
vector<int> minSubsequence(vector<int>& nums) {
sort(nums.begin(), nums.end(),greater<int>());
vector<int> res;
int sum = 0;
for(int i: nums)
sum += i;
int x=0;
for(int i=0; i<nums.size(); i++)
{
... | /**
* @param {number[]} nums
* @return {number[]}
*/
var minSubsequence = function(nums) {
const target = nums.reduce((a, b) => a + b) / 2;
nums.sort((a, b) => b - a);
let i = 0, sum = 0;
while (sum <= target) {
sum += nums[i++];
}
return nums.slice(0, i);
}; | Minimum Subsequence in Non-Increasing Order |
You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.
We want to place these books in order onto bookcase shelves that have a total width shelfWidth.
We choose some of the books to place on this shelf such that... | class Solution:
def minHeightShelves(self, books, shelf_width: int) -> int:
n, dp = len(books), [float('inf')] * (len(books)+1)
dp[0] = 0
for i in range(1, n+1):
max_width, max_height, j = shelf_width, 0, i - 1
while j >= 0 and max_width - books[j][0] >=... | class Solution {
int[][] books;
int shefWidth;
Map<String, Integer> memo = new HashMap();
public int findMinHeight(int curr, int maxHeight, int wRem) {
String key = curr + ":" + wRem ;
if(memo.containsKey(key)) return memo.get(key);
if(curr == books.length ) return ... | class Solution {
public:
int minHeightShelves(vector<vector<int>>& books, int shelfWidth) {
int n=books.size();
vector<vector<int>> cost(n+1,vector<int>(n+1));
for(int i=1;i<=n;i++)
{
int height=books[i-1][1];
int width=books[i-1][0];
cost[i][i]=he... | var minHeightShelves = function(books, shelfWidth) {
let booksArr = []
for(let i = 0; i < books.length; i++) {
let remainingWidth = shelfWidth - books[i][0]
let bookHeight = books[i][1]
let maxHeight = bookHeight
let prevSum = booksArr[i - 1] !== undefined ? booksArr[i - 1] : ... | Filling Bookcase Shelves |
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and yo... | class Solution:
def firstBadVersion(self, n: int) -> int:
fast, slow = int(n/2), n
diff = abs(fast-slow)
while isBadVersion(fast) == isBadVersion(slow) or diff > 1:
fast, slow = fast + (-1)**isBadVersion(fast) * (int(diff/2) or 1), fast
diff = abs(fast-slow)
r... | /* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int s = 0; int e = n;
while(s < e) {
int mid = s +(e-s)/2;
... | class Solution {
public:
int firstBadVersion(int n) {
//Using Binary Search
int lo = 1, hi = n, mid;
while (lo < hi) {
mid = lo + (hi - lo) / 2;
if (isBadVersion(mid)) hi = mid;
else lo = mid+1;
}
return lo;
}
}; | /**
* Definition for isBadVersion()
*
* @param {integer} version number
* @return {boolean} whether the version is bad
* isBadVersion = function(version) {
* ...
* };
*/
/**
* @param {function} isBadVersion()
* @return {function}
*/
var solution = function(isBadVersion) {
/**
* @param {integer} n T... | First Bad Version |
You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.
You can perform the following operation at most maxOperations times:
Take any bag of balls and divide it into two new bags with a positive number of balls.
For example, a bag of 5 balls ca... | class Solution:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
l, r = 1, max(nums)
while l < r:
mid = (l + r) // 2
if sum([(n - 1) // mid for n in nums]) > maxOperations:
l = mid + 1
else:
r = mid
return... | class Solution {
public int minimumSize(int[] nums, int maxOperations) {
//initiate the boundary for possible answers, here if you let min=1 it will still work for most cases except for some corner cases. We make max=100000000 because nums[i] <= 10^9. You can choose to sort the array and make the max= arr.max, at ... | class Solution {
public:
bool isPossible(vector<int>&nums,int mid_penalty,int maxOperations)
{
int operations=0;
for(int i=0;i<nums.size();i++)
{
operations+=(nums[i]/mid_penalty); //Operations Nedded to divide that element.
if(nums[i]%mid_penalty==0) //if it is ... | var minimumSize = function(nums, maxOperations) {
let i = 1
let j = Math.max(...nums)
while (i <= j) {
let mid = Math.floor((j-i)/2 + i)
let count = 0
nums.forEach(n => count += Math.floor((n-1)/mid))
if (count <= maxOperations) {
j = mid - 1
} else {
i = mid + 1
}
}
retu... | Minimum Limit of Balls in a Bag |
You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any... | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
def helper(row,col,count):
for c in range(len(grid[0])):
if c == col:
continue
if grid[row][c] == 1:
count += 1
return count
... | class Solution {
int []parent;
int []rank;
public int countServers(int[][] grid) {
parent=new int[grid.length*grid[0].length];
rank=new int[grid.length*grid[0].length];
for(int i=0;i<parent.length;i++){
parent[i]=i;
rank[i]=0;
}
for(int i=0;i<g... | class Solution {
public:
int countServers(vector<vector<int>>& grid) {
int n=grid.size(),m=grid[0].size();
vector<vector<bool>>visited(n,vector<bool>(m,false));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j] && !visited[i][j])
... | var countServers = function(grid) {
const m = grid.length;
const n = grid[0].length;
const lastRows = [];
const lastCols = [];
const set = new Set();
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
... | Count Servers that Communicate |
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) Adds word to the data structure, it can be matched later.
bool search(word) Returns true if ... | class TrieNode:
def __init__(self, val):
self.val = val
self.children = {}
self.isEnd = False
class WordDictionary:
def __init__(self):
self.root = TrieNode("*")
def addWord(self, word: str) -> None:
curr = self.root
for c in... | class WordDictionary {
private class Node{
boolean last;
Node[] sub;
Node(){
last = false;
sub = new Node[26];
}
}
Node root;
public WordDictionary() {
root = new Node();
}
public void addWord(String word) {
No... | class WordDictionary {
public:
struct tr {
bool isword;
vector<tr*> next;
tr() {
next.resize(26, NULL);
isword = false;
}
};
tr *root;
WordDictionary() {
root = new tr();
}
void addWord(string word) {
tr *cur = root;
... | var WordDictionary = function() {
this.aryWordList = [];
};
/**
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.addWord = function(word) {
this.aryWordList.push(word);
};
/**
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.search = function(word) {
const... | Design Add and Search Words Data Structure |
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a desce... | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if ((root.val >= p.val) and (root.val <= q.val)) or ((root.val >= q.val) and (root.val <= p.val)):
return root
elif (root.val > p.val):
return self.lowestC... | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root ... | class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(p->val<root->val && q->val<root->val) return lowestCommonAncestor(root->left,p,q);
else if(p->val>root->val && q->val>root->val) return lowestCommonAncestor(root->right,p,q);
return root;
... | var lowestCommonAncestor = function(root, p, q) {
while(root){
if(p.val>root.val && q.val>root.val){
root=root.right
}else if(p.val<root.val && q.val<root.val){
root=root.left
}else{
return root
}
}
} | Lowest Common Ancestor of a Binary Search Tree |
You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.
Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 +... | class Solution:
def colorTheGrid(self, m: int, n: int) -> int:
from functools import reduce
MOD = 10**9 + 7
sum_mod = lambda x,y: (x+y)%MOD
def normalize(pat_var):
mapping = { e:i+1 for i, e in enumerate(pat_var[0:2]) }
mapping[list({1,2,3}.difference... | class Solution
{
static int mod=(int)(1e9+7);
public static int dfs(int n,ArrayList<ArrayList<Integer>> arr,int src,int dp[][])
{
if(n==0)
{
return 1;
}
if(dp[n][src]!=-1)
{
return dp[n][src];
}
int val=0;
for(Integer ap:arr.get(src))... | vector<string> moves;
int MOD = 1e9 + 7;
void fill(string s, int n, int p){
if(n==0){
moves.push_back(s);
return;
}
for(int i=1; i<4; i++){
if(p==i){
continue;
}
string m = to_string(i);
fill(s+m, n-1, i);
}
return;
}
class Solution {
publi... | // transform any decimal number to its ternary representation
let ternary=(num,len)=>{
let A=[],times=0
while(times++<len)
A.push(num%3),num= (num-num%3)/3
return A
}
// deduce whether my array does not contain 2 consecutive elements
let adjdiff=Array=>Array.every((d,i)=>i==0||d!==Array[i-1])
//main... | Painting a Grid With Three Different Colors |
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only.
For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords.
The conversion ope... | # Brute Force
# O(S * T); S := len(startWors); T := len(targetWords)
# TLE
class Solution:
def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:
cnt = 0
for target in targetWords:
for start in startWords:
if len(target) - len(start) == 1 and len(set(l... | class Solution {
public int wordCount(String[] startWords, String[] targetWords) {
int n = startWords.length;
int count = 0;
Set<String> set = new HashSet<>();
//1. store lexicographically sorted letters of startword in set
for(String start: startWords){
... | class Solution {
public:
int wordCount(vector<string>& startWords, vector<string>& targetWords) {
set<vector<int>> hash;
for (int i = 0; i < startWords.size(); i++) {
vector<int> counter(26, 0);
for (char &x : startWords[i]) {
counter[x - 'a']++;
}... | var wordCount = function(startWords, targetWords) {
const startMap = {};
for(let word of startWords) {
startMap[word.split('').sort().join('')] = true;
}
let ans = 0;
for(let word of targetWords) {
for(let i=0;i<word.length;i++) {
let temp = (word.substring(0,i) + word.s... | Count Words Obtained After Adding a Letter |
Given a binary tree root and an integer target, delete all the leaf nodes with value target.
Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).
Example 1:
Inpu... | class Solution:
def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:
if not root:
return None
root.left = self.removeLeafNodes(root.left, target)
root.right = self.removeLeafNodes(root.right, target)
if not root.left and not root.right a... | class Solution {
public TreeNode removeLeafNodes(TreeNode root, int target) {
if(root==null)
return root;
root.left = removeLeafNodes(root.left,target);
root.right = removeLeafNodes(root.right,target);
if(root.left == null && root.right == null && root.val == target)
... | /**
* 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) ... | var removeLeafNodes = function(root, target) {
const parent = new TreeNode(-1, root, null);
const traverse = (r = root, p = parent, child = -1) => {
if(!r) return null;
traverse(r.left, r, -1);
traverse(r.right, r, 1);
if(r.left == null && r.right == null && r.val == target) {
... | Delete Leaves With a Given Value |
There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.
In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.
Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top t... | class Solution:
def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:
n = len(piles)
prefixSum = []
for i in range(n):
temp = [0]
for j in range(len(piles[i])):
temp.append(temp[-1] + piles[i][j])
prefixSum.append(temp)
... | class Solution {
public int maxValueOfCoins(List<List<Integer>> piles, int k) {
int n = piles.size();
int[][] ans = new int[n+1][2001];
Collections.sort(piles, (List<Integer> a, List<Integer> b) -> b.size() - a.size());
for(int i = 1; i <= k; i++) {
for(int j = 1; j <= n;... | class Solution {
public:
int dp[1001][2001]; //Dp array For Memoization.
int solve(vector<vector<int>>&v,int index,int coin)
{
if(index>=v.size()||coin==0) //Base Condition
return 0;
if(dp[index][coin]!=-1) //Check wheather It is Already Calculated Or not.
return dp[index][c... | /**
* @param {number[][]} piles
* @param {number} k
* @return {number}
*/
var maxValueOfCoins = function(piles, k) {
var n = piles.length;
var cache = {};
var getMax = function(i, k) {
if (i >= n || k <= 0) return 0;
var key = i + ',' + k;
if (cache[key] !== undefined) retur... | Maximum Value of K Coins From Piles |
There are n couples sitting in 2n seats arranged in a row and want to hold hands.
The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with t... | class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
count = 0
for i in range(0, len(row)-2, 2):
idx = i+1
if(row[i]%2 == 0):
n = (row[i] + 2)//2
newNo = 2*n - 1
else:
n = (row[i] + 1) //2;
... | class Solution {
public int minSwapsCouples(int[] row) { // Union -Find pairs for 2
Map<Integer,Integer> parents=new HashMap<>();
int count=0;
for(int i=0;i<row.length;i+=2){
int parent=Math.min(row[i],row[i+1]);
int child=Math.max(row[i],row[i+1]);
parent... | class Solution {
public:
int minSwapsCouples(vector<int>& row) {
int cnt=0,n=row.size();
// first of all making row element equal ex for [0,1],[2,3] --> [0,0] ,[2,2]
for(auto &x : row){
if(x&1){
x--;
}
}
for( int i=0; i<n; i+=2){
int ele=row[i];
int j=i+1;
// for every num find location ... | /**
* @param {number[]} row
* @return {number}
*/
var minSwapsCouples = function(row) {
let currentPositions = [];
for(let i=0;i<row.length;i++){
currentPositions[row[i]]=i;
}
let swapCount = 0;
for(let j=0;j<row.length;j+=2) // Looping through the couches
{
let leftPart... | Couples Holding Hands |
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Expla... | class Solution(object):
def hasPathSum(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: bool
"""
if not root: return False
targetSum -= root.val
if not root.left and not root.right:
return not targetSum
... | class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
if(root.left == null && root.right == null) return root.val == targetSum;
return hasPathSum(root.right, targetSum - root.val) || hasPathSum(root.left, targetSum - root.val);
... | class Solution {
public:
bool ans=false;
int sum=0;
void recur(TreeNode* root, int target){
if(root==NULL)return;
sum+=root->val;
recur(root->left,target);
recur(root->right,target);
if(root->left==NULL && root->right==NULL&&sum == target){ /... | var hasPathSum = function(root, targetSum) {
return DFS(root, 0 , targetSum)
};
const DFS = (curr, currentSum, targetSum) =>{
if(!curr) return false
currentSum += curr.val;
if(!curr.left && !curr.right) return currentSum === targetSum;
return DFS(curr.left, currentSum, targetSum) || DFS(curr.right, currentSum... | Path Sum |
You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:
You can place the boxes anywhere on the floor.
If box x is placed on top o... | class Solution:
def minimumBoxes(self, n: int) -> int:
r = 0
while (n_upper := r*(r+1)*(r+2)//6) < n:
r += 1
m = r*(r+1)//2
for i in range(r, 0, -1):
if (n_upper - i) < n:
break
n_upper -= i
m -= 1
return m | class Solution {
static final double ONE_THIRD = 1.0d / 3.0d;
public int minimumBoxes(int n) {
int k = findLargestTetrahedralNotGreaterThan(n);
int used = tetrahedral(k);
int floor = triangular(k);
int unused = (n - used);
if (unused == 0) {
return floor;
... | class Solution {
public:
int minimumBoxes(int n) {
// Find the biggest perfect pyramid
uint32_t h = cbrt((long)6*n);
uint32_t pyramid_box_num = h*(h+1)/2*(h+2)/3; // /6 is split to /2 and /3 to avoid long to save space
if ( pyramid_box_num > n ){
h--;
... | var minimumBoxes = function(n) {
//Binary search for the height of the biggest triangle I can create with n cubes available.
let lo=1,hi=n,result
let totalCubes=x=>x*(x+1)*(x+2)/6 //the total cubes of a triangle with height x
while(lo+1<hi){
let mid=lo+hi>>1
if(totalCubes(mid)<=n)
... | Building Boxes |
Given the root of a binary tree, return the sum of values of its deepest leaves.
Example 1:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15
Example 2:
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19
Constraints:
The number of nodes in the tree is in the ra... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
"""
THOUGHT PROCESS:
1) find the height of the tree, this way we would know... | class Solution {
public int height(TreeNode root)
{
if(root == null)
return 0;
return Math.max(height(root.left), height(root.right)) + 1;
}
public int deepestLeavesSum(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) ret... | ** #Vote if u like ❤️**
class Solution {
public:
void fun(TreeNode *root , int l , map<int , vector<int>> &m)
{
if(root == NULL) return; //If root is NULL it will return
m[l].push_back(root -> val); //With level as key inserting the value to the vector
fun(root -> left, l + 1, m); // passi... | var deepestLeavesSum = function(root) {
let queue = [];
queue.push([root, 0]);
let sum = 0;
let curLevel = 0
let i = 0;
while(queue.length-i > 0) {
let [node, level] = queue[i];
queue[i] = null;
i++;
if(level > curLevel) {
sum = 0;
curLevel... | Deepest Leaves Sum |
Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not ... | class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
## RC ##
## APPROACH : STACK ##
## LOGIC ##
## 1. Use Monotonic Increasing Stack Concept
## 2. Main idea is to find the Next Smaller Element in O(N) using #1
stack = []
for i, num in enume... | class Solution {
public int[] finalPrices(int[] prices) {
for(int i = 0; i < prices.length; i++){
for(int j = i + 1; j < prices.length; j++){
if(j > i && prices[j] <= prices[i]){
prices[i] -= prices[j];
break;
}
... | class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
vector<int>sk;
for(int i=0;i<prices.size();i++){
int discount=prices[i];
for(int j=i+1;j<prices.size();j++){
if(prices[i]>=prices[j]){
discount=prices[i]-prices[j];
... | var finalPrices = function(prices) {
let adjPrices = [];
while(prices.length) {
let currentPrice = prices[0];
// Remove first price in original array
// Since we're looking for a price less than or equal to
prices.shift();
let lowerPrice = prices.find((a... | Final Prices With a Special Discount in a Shop |
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1... | class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
lis = nums1 + nums2
lis.sort()
hi = len(lis)
print(5/2)
if hi%2 == 0:
if (lis[hi/2] + lis[hi/2-1])%2 == 0:
return (lis[hi/2] + lis[hi/2-1] )/2
return (lis[hi/2] + l... | class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if(nums1.length==1 && nums2.length==1) return (double)(nums1[0]+nums2[0])/2.0;
int i = 0;
int j = 0;
int k = 0;
int nums[] = new int[nums1.length + nums2.length];
if(nums1.length !=0 && ... | class Solution {
public:
//Merging two arrays :-
vector<int> mergeSortedArrays(vector<int>&arr1,vector<int>&arr2){
int n = arr1.size();
int m = arr2.size();
vector<int> ans(m+n);
int i = 0;
int j = 0;
int mainIndex = 0;
while( i < n && ... | var findMedianSortedArrays = function(nums1, nums2) {
let nums3 = nums1.concat(nums2).sort((a,b) => a - b)
if(nums3.length % 2 !== 0) return nums3[(nums3.length-1)/2]
return (nums3[nums3.length/2] + nums3[nums3.length/2 - 1])/2
}; | Median of Two Sorted Arrays |
You are given an array of strings products and a string searchWord.
Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the th... | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
sorted_products = sorted(products)
res = []
prefix = ''
for letter in searchWord:
prefix += letter
words = []
for product in sorted_products:
... | class Solution
{
public List<List<String>> suggestedProducts(String[] products, String searchWord)
{
PriorityQueue<String> pq= new PriorityQueue<String>();
List<List<String>> res= new LinkedList<List<String>>();
List<String> segment= new LinkedList<String>();
for(int i=0;i<produc... | class Solution {
public:
vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
map<int, vector<string>> m;
vector<vector<string>> res;
for (int i = 0; i < products.size(); i++)
{
int j = 0;
while (products[i][j] == searchWord[... | function TrieNode(key) {
this.key = key
this.parent = null
this.children = {}
this.end = false
this.getWord = function() {
let output = []
let node = this
while(node !== null) {
output.unshift(node.key)
node = node.parent
}
return output.join('')
}
}
function ... | Search Suggestions System |
A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.
Example 1:
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: se... | class Solution:
def checkIfPangram(self, sentence: str) -> bool:
return len(set(sentence))==26 | class Solution {
public boolean checkIfPangram(String sentence) {
int seen = 0;
for(char c : sentence.toCharArray()) {
int ci = c - 'a';
seen = seen | (1 << ci);
}
return seen == ((1 << 26) - 1);
}
} | class Solution {
public:
bool checkIfPangram(string sentence) {
vector<int> v(26,0);
for(auto x:sentence)
{
v[x-'a'] = 1;
}
return accumulate(begin(v),end(v),0) == 26;
}
}; | var checkIfPangram = function(sentence) {
return new Set(sentence.split("")).size == 26;
}; | Check if the Sentence Is Pangram |
On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].
Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.
We may make the following moves:
'U' moves our position up one row, if the position exists on the board;
'D' moves our ... | class Solution:
def alphabetBoardPath(self, target: str) -> str:
def shortestPath(r,c,tr,tc):
path = ""
pr = r
while r > tr:
path += 'U'
r -= 1
while r < tr:
path += 'D'
r += 1
if tr =... | class Solution {
public String alphabetBoardPath(String target) {
int x = 0, y = 0;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < target.length(); i++){
char ch = target.charAt(i);
int x1 = (ch - 'a') / 5;
int y1 = (ch - 'a') % 5;
... | class Solution {
public:
string alphabetBoardPath(string target) {
string ans = "";
int prevRow = 0;
int prevCol = 0;
int curRow = 0;
int curCol = 0;
for(int i = 0; i < target.length(); i++){
prevCol = curCol;
prevRow = curRow;
curR... | var alphabetBoardPath = function(target) {
var result = "";
var list = "abcdefghijklmnopqrstuvwxyz";
var curr = 0;
for(i=0;i<target.length;i++){
let next = list.indexOf(target[i]);
if(next!==curr){
if(curr===25) curr-=5, result+="U";
if(next%5!==curr%5... | Alphabet Board Path |
You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:
1 <= pivot < n
nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]
You are also given an integer k. You can c... | class Solution:
def waysToPartition(self, nums: List[int], k: int) -> int:
prefix_sums = list(accumulate(nums))
total_sum = prefix_sums[-1]
best = 0
if total_sum % 2 == 0:
best = prefix_sums[:-1].count(total_sum // 2) # If no change
after_counts = Counter(total_s... | class Solution {
//time - O(n), space - O(n)
public int waysToPartition(int[] nums, int k) {
int n = nums.length;
int[] pref = new int[n];
pref[0] = nums[0];
Map<Integer, Integer> count = new HashMap<>(); //contribution of prefixes without changing
count.put(pref[0], 1);... | class Solution {
public:
int waysToPartition(vector<int>& nums, int k) {
unordered_map<long long int,int> left;
unordered_map<long long int,int> right;
long long int sum=accumulate(nums.begin(),nums.end(),0L);
long long int leftSum=0;
int n=nums.size();
for(int i=0... | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var waysToPartition = function(nums, k) {
let totalSum=nums.reduce((acc, curr) => acc+curr)
let left=0;
let rightDiff={}
let leftDiff={}
for(let i=0; i<nums.length-1; i++) {
left+=nums[i]
const right=tota... | Maximum Number of Ways to Partition an Array |
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Example 1:
... | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
def util(node: TreeNode, sum_array) -> int:
t = [e - node.val for e in sum_array]
zeroes = t.count(0)
if node.left is None and node.right is None:
return zeroes
... | class Solution {
public int pathSum(TreeNode root, int targetSum) {
HashMap<Long, Integer> hm = new HashMap<>();
//hm.put(0L,1); ---> can use this to handle initial condition if c_sum == target sum
int res = solve(hm, root, targetSum, 0);
return res;
}
public int solve(Has... | class Solution {
public:
int ans = 0,t;
void dfs(unordered_map<long long,int> &curr,TreeNode* node,long long sm){
if(!node){
return;
}
sm += (long long) node->val;
ans += curr[sm-t];
curr[sm]++;
dfs(curr,... | var pathSum = function(root, targetSum) {
let count = 0;
let hasSum = (node, target) => { //helper function, calculates number of paths having sum equal to target starting from given node
if(node===null){// base case
return;
}
if(node.val===target){// if at any point path sum meets the requirement
... | Path Sum III |
A happy string is a string that:
consists only of letters of the set ['a', 'b', 'c'].
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given t... | class Solution:
def getHappyString(self, n: int, k: int) -> str:
ans = []
letters = ['a','b','c']
def happystr(n,prev,temp):
if n==0:
ans.append("".join(temp))
return
for l in letters:
if l!=prev:
... | class Solution {
public String getHappyString(int n, int k) {
List<String> innerList = new ArrayList<>();
getHappyStringUtil(n, k, new char[] { 'a', 'b', 'c' }, new StringBuilder(), innerList);
if (innerList.size() < k)
return "";
return innerList.get(k - 1);
}
pub... | class Solution {
private:
void happy(string s, vector<char> &v, int n, vector<string> &ans){
if(s.size() == n){
ans.push_back(s);
return;
}
for(int i=0; i<3; i++){
if(s.back() != v[i]){
s.push_back(v[i]);
happy(s,v,n,ans... | var getHappyString = function(n, k) {
const arr = ['a','b','c'], finalArr = ['a','b','c'];
let chr = '', str = '';
if(finalArr[finalArr.length-1].length === n && finalArr[0].length === n ) {
return finalArr[k-1] && finalArr[k-1].length === n ? finalArr[k-1] : '';
}
for(; finalArr.length < k ... | The k-th Lexicographical String of All Happy Strings of Length n |
Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.
For a given query word, the spell checker handles two categories of spelling mistakes:
Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same c... | class Solution:
def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:
n = len(wordlist)
d = {}
sd = {}
vd = {}
cd = {}
for i in range(n):
d[wordlist[i]] = i
s = wordlist[i].lower()
if s not in sd:sd[s] = i
... | class Solution {
public String[] spellchecker(String[] wordlist, String[] queries) {
String[] ans = new String[queries.length];
Map<String, String>[] map = new HashMap[3];
Arrays.setAll(map, o -> new HashMap<>());
String pattern = "[aeiou]";
for (String w : wordlist){
... | class Solution {
public:
vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) {
unordered_map<string, vector<int>> umap;
// step 1: add info in umap;
for(int curr = 0; curr < wordlist.size(); curr++){
// case 1: add same;
umap[wordlist[curr]... | var spellchecker = function(wordlist, queries) {
const baseList = new Set(wordlist.reverse());
const loweredList = wordlist.reduce((map, word) => (map[normalize(word)] = word, map), {});
const replacedList = wordlist.reduce((map, word) => (map[repVowels(word)] = word, map), {});
return queries.map(word => (
... | Vowel Spellchecker |
There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.
Return ... | class Solution:
def bulbSwitch(self, n: int) -> int:
return int(sqrt(n)) | class Solution {
public int bulbSwitch(int n) {
return (int)Math.sqrt(n);
}
} | class Solution {
public:
int bulbSwitch(int n) {
return sqrt(n);
}
}; | var bulbSwitch = function(n) {
return Math.floor(Math.sqrt(n));
}; | Bulb Switcher |
You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).
The valid times are those inclusively between 00:00 and 23:59.
Return the latest valid time you can get from time by replacing the hidden digits.
Example 1:
Input: time = "2?:?0"
Output: "... | class Solution:
def maximumTime(self, time: str) -> str:
memo = {"0":"9",
"1":"9",
"?":"3",
"2":"3"}
answer = ""
for idx, val in enumerate(time):
if val == "?":
if idx == 0:
if time[idx+1] == "?":
answer += "2"... | class Solution {
public String maximumTime(String time) {
char[] times = time.toCharArray();
//for times[0]
//if both characters of hour is ?, then hour is 23 then times[0] should be '2'("??:3?)".
//if 2nd character of hour is <= 3, then hour can be in 20s then times[0] should be '2... | class Solution {
public:
string maximumTime(string time) {
//for time[0]
//if both characters of hour is ?, then hour is 23 then time[0] should be '2'("??:3?)".
//if 2nd character of hour is <= 3, then hour can be in 20s then time[0] should be '2'.
//if 2nd character of hour is >3, ... | var maximumTime = function(time) {
time = time.split('')
if (time[0] === "?") time[0] = time[1] > 3 ? "1" : "2"
if (time[1] === "?") time[1] = time[0] > 1 ? "3" : "9"
if (time[3] === "?") time[3] = "5"
if (time[4] === "?") time[4] = "9"
return time.join('')
}; | Latest Time by Replacing Hidden Digits |
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.
The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be... | """
approach:
first replace - with +- in the string so that implementation gets
a little easy
"""
class Solution:
def fractionAddition(self, expression: str) -> str:
expression = expression.replace('-', '+-')
parts = [item for item in expression.split('+') if item != '']
numes, denoms, denom... | class Solution {
private int gcd(int x, int y){
return x!=0?gcd(y%x, x):Math.abs(y);
}
public String fractionAddition(String exp) {
Scanner sc = new Scanner(exp).useDelimiter("/|(?=[-+])");
int A=0, B=1;
while(sc.hasNext()){
int a = sc.nextInt(), b=sc.nextInt();... | class Solution {
public:
string fractionAddition(string expression) {
int res_num = 0; //keep track of numerator
int res_denom = 1; //keep track of denominator
char sign = '+'; //keep track of sign
for(int i = 0; i < expression.size(); i++){ //parse the expression string
... | var fractionAddition = function(expression) {
const fractions = expression.split(/[+-]/).filter(Boolean);
const operator = expression.split(/[0-9/]/).filter(Boolean);
expression[0] !== '-' && operator.unshift('+');
const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
const lcm = fractions.reduce((result, fraction) ... | Fraction Addition and Subtraction |
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
Example 1:
Input: nums = [3,2,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
Exam... | class Solution:
def thirdMax(self, nums: List[int]) -> int:
nums_set = set(nums)
sorted_set = sorted(nums_set)
return sorted_set[-3] if len(nums_set) >2 else sorted_set[-1]
#use set() to remove dups
#if len of nums after dups have been removed is at least 2,... | class Solution {
public int thirdMax(int[] nums) {
Integer first = null, second = null, third = null;
for(Integer num: nums){
if(num.equals(first) || num.equals(second) || num.equals(third)) continue;
if(first == null || num > first){
third = second;
... | class Solution {
public:
int thirdMax(vector<int>& nums) {
set<int>s;
for(int i=0;i<nums.size();i++){
s.insert(nums[i]);
}
if(s.size()>=3){ // when set size >=3 means 3rd Maximum exist(because set does not contain duplicate element)
int Third_index_from_last... | var thirdMax = function(nums) {
nums.sort((a,b) => b-a);
//remove duplicate elements
for(let i=0; i<nums.length;i++){
if(nums[i] === nums[i+1]){
nums.splice(i+1, 1);
i--
}
}
return nums[2] !=undefined?nums[2]: nums[0]
}; | Third Maximum Number |
You are given two sorted arrays of distinct integers nums1 and nums2.
A valid path is defined as follows:
Choose array nums1 or nums2 to traverse (from index-0).
Traverse the current array from left to right.
If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to th... | from itertools import accumulate
class Solution:
def maxSum(self, nums1: List[int], nums2: List[int]) -> int:
acc1 = list(accumulate(nums1, initial = 0))
acc2 = list(accumulate(nums2, initial = 0))
i, j = len(nums1)-1, len(nums2)-1
previ, prevj = len(nums1), len(nums2)
prev_m... | class Solution {
public int maxSum(int[] nums1, int[] nums2) {
long currSum = 0, sum1 = 0, sum2 = 0;
int i = 0;
int j = 0;
while(i < nums1.length && j < nums2.length){
if(nums1[i] == nums2[j]) {
currSum += Math.max(sum1, sum2) + nums2[j];
s... | #define ll long long
class Solution {
public:
ll dp1[100005];
ll dp2[100005];
ll mod=1e9+7;
ll func(vector<int> &nums1 , vector<int> &nums2 , unordered_map< int , int> &mp1,
unordered_map< int , int> &mp2 , int i1 , int i2 , int n1 , int n2 , bool f1)
{
if(i1>=n1 || i2>=n2)
... | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var maxSum = function(nums1, nums2) {
let MODULO_AMOUNT = 10 ** 9 + 7;
let result = 0;
let ptr1 = 0;
let ptr2 = 0;
let n1 = nums1.length;
let n2 = nums2.length;
let section_sum1 = 0;
let section_sum2 = 0;
... | Get the Maximum Score |
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words.
For example, if words = ["abc", "xyz"] and the stream added the four characters (one by one) 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix "xyz" ... | class TrieNode:
def __init__(self):
self.children = {}
self.endOfWord = False
class StreamChecker:
def __init__(self, words: List[str]):
self.root = TrieNode()
self.qCur = self.root
self.stream = collections.deque()
cur = self.root
for word in words... | class StreamChecker {
class TrieNode {
boolean isWord;
TrieNode[] next = new TrieNode[26];
}
TrieNode root = new TrieNode();
StringBuilder sb = new StringBuilder();
public StreamChecker(String[] words) {
createTrie(words);
}
public boolean query(ch... | class StreamChecker {
struct Trie {
Trie* suffixLink; //this is where it will fallback to when a letter can't be matched
int id = -1; //this id will be 0 or greater if it matches a word
map<char, Trie*> next;
};
public:
Trie* root;
Trie* queryPtr;
int uniqueIds = 0; //used to... | var StreamChecker = function(words) {
function Trie() {
this.suffixLink = null; //this is where it will fallback to when a letter can't be matched
this.id = -1; //this id will be 0 or greater if it matches a word
this.next = new Map(); //map of <char, Trie*>
}
this.root = new Trie();... | Stream of Characters |
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.
The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a ... | class Solution(object):
def countStudents(self, students, sandwiches):
"""
:type students: List[int]
:type sandwiches: List[int]
:rtype: int
"""
while sandwiches:
if sandwiches[0] in students:
students.remove(sandwiches[0])
... | class Solution {
public int countStudents(int[] students, int[] sandwiches) {
int ones = 0; //count of students who prefer type1
int zeros = 0; //count of students who prefer type0
for(int stud : students){
if(stud == 0) zeros++;
else ones++;
}
// fo... | class Solution {
public:
int countStudents(vector<int>& students, vector<int>& sandwiches) {
int size = students.size();
queue<int> student_choice;
for(int i = 0 ; i < size ; ++i){
student_choice.push(students[i]);
}
int rotations = 0 , i = 0;
while(studen... | var countStudents = function(students, sandwiches) {
while (students.length>0 && students.indexOf(sandwiches[0])!=-1) {
if (students[0] == sandwiches[0]) {
students.shift();
sandwiches.shift();
}
else students.push(students.shift());
}
return students.length
}; | Number of Students Unable to Eat Lunch |
Given a string s. Return all the words vertically in the same order in which they appear in s.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column there will be only one word.
... | class Solution:
def getMaxLen(self, words):
max_len = 0
for word in words:
max_len = max(max_len, len(word))
return max_len
def printVertically(self, s: str) -> List[str]:
words = s.split()
max_len = self.getMaxLen(words)
res = list()
... | class Solution {
public List<String> printVertically(String s) {
s = s.replace(" ",",");
String str="";
List<String> a=new ArrayList<>();
int max=0;
for(int i =0;i<s.length();i++){
char ch=s.charAt(i);
if(ch==','){
a.add(str);
... | class Solution {
public:
vector<string> printVertically(string s) {
int row = 0, col = 0;
stringstream sso(s);
string buffer;
while (sso >> buffer)
{
row++;
col = max((int)buffer.size(),col);
}
vector<vector<char>> matrix(row, vecto... | /**
* @param {string} s
* @return {string[]}
*/
var printVertically = function(s)
{
let arr = s.split(' '),
max = arr.reduce((last, curr) => Math.max(last, curr.length), 0),
ans = [];
arr = arr.map(el => el + ' '.repeat(max - el.length));
for (let i = 0; i < max; i++)
{
le... | Print Words Vertically |
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative posit... | class Solution:
def maxDotProduct(self, A, B):
dp = [float('-inf')] * (len(B)+1)
for i in range(len(A)):
prev = float('-inf')
for j in range(len(B)):
product = A[i] * B[j]
prev, dp[j+1] = dp[j+1], max(dp[j+1], dp[j], product, prev + product)
... | class Solution {
public int maxDotProduct(int[] nums1, int[] nums2) {
int N = nums1.length, M = nums2.length;
int[][] dp = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
dp[i][j] = nums1[i] * nums2[j];
if (i > 0 && j > 0... | class Solution
{
public:
const int NEG_INF = -10e8;
int maxDotProduct(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
int m = nums2.size();
// NOTE : we can't initialize with INT_MIN because adding any val with it will give overflow
// that is why w... | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var maxDotProduct = function(nums1, nums2) {
var m = nums1.length;
var n = nums2.length;
if (!m || !n) return 0;
var dp = [[nums1[0] * nums2[0]]];
for (var i = 1; i < m; i++) {
dp[i] = [];
dp[i][0] = Ma... | Max Dot Product of Two Subsequences |
A string is considered beautiful if it satisfies the following conditions:
Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.
The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).
For example, strings "aeiou" and "aaaaaaeiiii... | class Solution:
def longestBeautifulSubstring(self, word: str) -> int:
g = ''
count = m = 0
for x in word:
if g and x < g[-1]:
count = 0
g = ''
if not g or x > g[-1]:
g += x
count += 1
if g == 'ae... | class Solution {
public int longestBeautifulSubstring(String word) {
int max = 0;
for(int i = 1;i<word.length();i++){
int temp = 1;
Set<Character> verify = new HashSet<>();
verify.add(word.charAt(i-1));
while(i < word.length() && word.charAt(i) >= word.charAt(i-1)){
... | class Solution {
public:
int longestBeautifulSubstring(string word) {
const auto n = word.size();
int cnt = 1;
int len = 1;
int max_len = 0;
for (int i = 1; i != n; ++i) {
if (word[i - 1] == word[i]) {
++len;
} else if (word[i - 1] < w... | /**
* @param {string} word
* @return {number}
*/
var longestBeautifulSubstring = function(word) {
let obj = { 'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5 }
let seq = 0
let maxstrcount = 0, strcount = ""
for (let i = 0; i <= word.length; i++) {
if (seq <= obj[word[i]]) {
strcount +=... | Longest Substring Of All Vowels in Order |
You are given two integers n and maxValue, which are used to describe an ideal array.
A 0-indexed integer array arr of length n is considered ideal if the following conditions hold:
Every arr[i] is a value from 1 to maxValue, for 0 <= i < n.
Every arr[i] is divisible by arr[i - 1], for 0 < i < n.
Ret... | from math import sqrt
class Solution:
def primesUpTo(self, n):
primes = set(range(2, n + 1))
for i in range(2, n):
if i in primes:
it = i * 2
while it <= n:
if it in primes:
primes.remove(it)
... | class Solution {
int M =(int)1e9+7;
public int idealArrays(int n, int maxValue) {
long ans = 0;
int N = n+maxValue;
long[] inv = new long[N];
long[] fact = new long[N];
long[] factinv = new long[N];
inv[1]=fact[0]=fact[1]=factinv[0]=factinv[1]=1;
for (int ... | int comb[10001][14] = { 1 }, cnt[10001][14] = {}, mod = 1000000007;
class Solution {
public:
int idealArrays(int n, int maxValue) {
if (comb[1][1] == 0) { // one-time computation.
for (int s = 1; s <= 10000; ++s) // nCr (comb)
for (int r = 0; r < 14; ++r)
comb[s][r] = r == 0 ? 1... | /**
* @param {number} n
* @param {number} maxValue
* @return {number}
*/
var idealArrays = function(n, maxValue) {
const mod = 1e9 + 7;
let cur = 0;
let arr = Array(2).fill().map(() => Array(maxValue).fill(1));
for (let l = 2; l <= n; l++) {
const prev = arr[cur];
const next = arr[1-cur];
for (l... | Count the Number of Ideal Arrays |
There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:
In each step, you will choose any 3 piles of coins (not necessarily consecutive).
Of your choice, Alice will pick the pile with the maximum number of coins.
You will pick the next pile with the maximum number of ... | class Solution:
def maxCoins(self, piles: List[int]) -> int:
piles.sort()
n = len(piles)
k = n // 3
i, j = 0, 2
ans = 0
while i < k:
ans += piles[n-j]
j += 2
i +=1
return ans | class Solution {
public int maxCoins(int[] piles) {
Arrays.sort(piles);
int s=0,n=piles.length;
for(int i=n/3;i<n;i+=2)
s+=piles[i];
return s;
}
} | class Solution {
public:
int maxCoins(vector<int>& piles) {
sort(piles.begin(),piles.end(),greater<int>());
int myPilesCount=0;
int myPilesSum=0;
int PilesSize=piles.size();
int i=1;
while(myPilesCount<(PilesSize/3))
{
myPilesSum+=piles[i];
... | var maxCoins = function(piles) {
let count = 0, i = 0, j = piles.length - 1;
piles.sort((a, b) => b - a);
while(i < j) {
count += piles[i + 1];
i += 2;
j--;
}
return count;
}; | Maximum Number of Coins You Can Get |
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).
For example, "Hello World", "HELLO", and "hello world hello world" are all sentences.
You are given a sentence s ... | class Solution:
def truncateSentence(self, s: str, k: int) -> str:
words = s.split(" ")
return " ".join(words[0:k]) | class Solution {
public String truncateSentence(String s, int k) {
int n = s.length();
int count = 0;
int i = 0;
while(i<n){
if(s.charAt(i)==' '){
count++;
if(count==k)
return s.substring(0,i);
}
... | class Solution {
public:
string truncateSentence(string s, int k) {
int n = s.size();
string ans;
int cnt = 0;
for(int i=0 ; i<n ; i++){
if(s[i] == ' '){
cnt++;
}
if(k == cnt){
return ans;
}
ans += s[i];
}
return ans;
}
}; | /**
* @param {string} s
* @param {number} k
* @return {string}
*/
var truncateSentence = function(s, k) {
return s.split(" ").slice(0,k).join(" ")
}; | Truncate Sentence |
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example 1:
Input: matrix = [[1,4,7... | class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
found=False
for X in matrix:
for M in X:
if M==target:
found=True
retu... | class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
int lo = 0, hi = rows;
while(lo + 1 < hi) {
int mid = lo + (hi - lo) / 2;
if (matrix[mid][0] <= target) {
lo = mid... | class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for(int i=0;i<matrix.size();++i)
{
int s=0,e=matrix[0].size()-1;
while(s<=e)
{
int mid=(s+e)/2;
if(matrix[i][mid]>target)
{
... | function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = parseInt((low + high) / 2);
if (arr[mid] == target) {
return mid;
}
else if (arr[mid] < target) {
low = mid + 1;
}
else if (a... | Search a 2D Matrix II |
Two strings are considered close if you can attain one from the other using the following operations:
Operation 1: Swap any two existing characters.
For example, abcde -> aecdb
Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the oth... | from collections import Counter
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
return set(word1) == set(word2) and Counter(Counter(word1).values()) == Counter(Counter(word2).values()) | class Solution {
private int N = 26;
public boolean closeStrings(String word1, String word2) {
// count the English letters
int[] arr1 = new int[N], arr2 = new int[N];
for (char ch : word1.toCharArray())
arr1[ch - 'a']++;
for (char ch : word2.toCharArray())
... | class Solution {
public:
bool closeStrings(string word1, string word2) {
set<int> w1_letters, w2_letters, w1_freq, w2_freq;
unordered_map<char, int> w1_m, w2_m;
for (auto a : word1) {
w1_letters.insert(a);
w1_m[a]++;
}
for (auto a : w... | var closeStrings = function(word1, word2) {
if (word1.length != word2.length) return false;
let map1 = new Map(), map2 = new Map(),freq1=new Set(),freq2=new Set();
for (let i = 0; i < word1.length; i++) map1.set(word1[i],map1.get(word1[i])+1||1),map2.set(word2[i],map2.get(word2[i])+1||1);
if (map1.size ... | Determine if Two Strings Are Close |
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [3.00000,14.50000,11.00000]
Explanation: The average value of nodes on level 0 is 3, o... | # 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:
# O(n) || O(h) where h is the height of the tree
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
queue = de... | class Solution {
public List<Double> averageOfLevels(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>(List.of(root));
List<Double> ans = new ArrayList<>();
while (q.size() > 0) {
double qlen = q.size(), row = 0;
for (int i = 0; i < qlen; i++) {
Tr... | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), l... | var averageOfLevels = function(root) {
let avg = [root.val];
let level = [];
let queue = [root];
while(queue.length>0){
let curr = queue.shift();
if(curr.left){
level.push(curr.left)
}
if(curr.right){
level.push(curr.right);
}
if(queue.length===0){
queue.push(...level);
... | Average of Levels in Binary Tree |
Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p =... | class Solution:
def isMatch(self, s, p):
n = len(s)
m = len(p)
dp = [[False for _ in range (m+1)] for _ in range (n+1)]
dp[0][0] = True
for c in range(1,m+1):
if p[c-1] == '*' and c > 1:
dp[0][c] = dp[0][c-2]
for r in range(1,n+1):
for c ... | class Solution {
public boolean isMatch(String s, String p) {
if (p == null || p.length() == 0) return (s == null || s.length() == 0);
boolean dp[][] = new boolean[s.length()+1][p.length()+1];
dp[0][0] = true;
for (int j=2; j<=p.length(); j++) {
dp[0][j] = p.charAt(j-1) ... | class Solution {
public:
bool isMatch(string s, string p) {
return helper(s,p,0,0);
}
bool helper(string s, string p, int i, int j)
{
if(j==p.length())
return i==s.length();
bool first_match=(i<s.length() && (s[i]==p[j] || p[j]=='.' ));
if(j+1<p.... | /**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
const pattern = new RegExp('^'+p+'$'); // ^ means start of string, $ means end of the string, these are to prevent certain pattern that match a part of the string to be returned as true.
return pattern.test(s)... | Regular Expression Matching |
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following:
0 represents a wall that you cannot pass through.
1 represents an empty cell that you can freely move to and from.
All other positive integers represent the ... | class Solution:
def highestRankedKItems(self, G, pricing, start, k):
m, n = len(G), len(G[0])
row, col = start
node = (0, G[row][col], row, col)
visited = set()
visited.add((row, col))
d = deque([node])
ans = []
while d:
dist, cost, row, c... | class Solution {
static class Quad
{
int x,y,price,dist;
Quad(int x,int y,int price,int dist)
{
this.x=x;
this.y=y;
this.price=price;
this.dist=dist;
}
}
public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pri... | class Solution {
public:
struct cell
{
int dist;
int cost;
int row;
int col;
};
struct compare
{
bool operator()(const cell &a, const cell &b)
{
if(a.dist != b.dist)
return a.dist < b.dist;
else if(a.cost != b.co... | var highestRankedKItems = function(grid, pricing, start, k) {
const m = grid.length;
const n = grid[0].length;
const dirs = [-1, 0, 1, 0, -1];
const visited = [];
for (let i = 0; i < m; ++i) {
visited[i] = new Array(n).fill(false);
}
const [low, high] = pricing;
const queue =... | K Highest Ranked Items Within a Price Range |
You are given an array of words where each word consists of lowercase English letters.
wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.
For example, "abc" is a predecessor of "abac", while ... | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=len)
dic = {}
for i in words:
dic[ i ] = 1
for j in range(len(i)):
# creating words by deleting a letter
... | class Solution {
Boolean compareForIncreaseByOne(String str1,String str2){
//str 1 will be long than str2
int first=0;
int second=0;
if(str1.length() != (str2.length() + 1)){
return false;
}
while(first < str1.length()){
if(second < st... | class Solution {
int dfs(unordered_map<string, int>& m, unordered_set<string>& setWords,
const string& w) {
if (m.count(w)) return m[w];
int maxLen = 1;
for(int i=0;i<w.size();++i) {
auto preWord = w.substr(0, i) + w.substr(i+1);
if(setWords.coun... | /**
* @param {string[]} words
* @return {number}
*/
var longestStrChain = function(words)
{
let tiers = new Array(16);
for(let i=0; i<tiers.length; i++)
tiers[i] = [];
for(let word of words)
tiers[word.length-1].push({word,len:1});
const isPredecessor... | Longest String Chain |
We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.
Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi... | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
def dfs(i, c):
if color[i] != 0:
if color[i] != c:
return False
return True
color[i] = c
for u in e[i]:
if not df... | class Solution {
int[] rank;
int[] parent;
int[] rival;
public boolean possibleBipartition(int n, int[][] dislikes) {
rank = new int[n+1];
rival = new int[n+1];
parent = new int[n+1];
for(int i = 1;i <= n;i++){
rank[i] = 1;
parent[i] = i;
}... | class Solution {
public:
bool dfs(vector<int>adj[], vector<int>& color, int node){
for(auto it: adj[node]){ //dfs over adjacent nodes
if(color[it]==-1){ //not visited yet
color[it]=1-color[node]; //set different color of adjacent nodes
if(!dfs(adj,color,it))... | var possibleBipartition = function(n, dislikes) {
const g = new Map();
dislikes.forEach(([a, b]) => {
const aDis = g.get(a) || [];
const bDis = g.get(b) || [];
g.set(a, aDis.concat(b));
g.set(b, bDis.concat(a));
});
const vis = new Array(n+1).fill(false);
const c... | Possible Bipartition |
You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.
You may jump forw... | class Solution:
def oddEvenJumps(self, arr: List[int]) -> int:
l = len(arr)
res = [False]*l
res[-1] = True
# for odd jump: for i, get next larger one
odd_next = [i for i in range(l)]
stack = [] # mono inc for ind
for n, i in sorted([(arr[i],... | class Solution {
public int oddEvenJumps(int[] arr) {
int len = arr.length;
int minjmp[] = new int[len];
int maxjmp[] = new int[len];
TreeMap<Integer, Integer> map = new TreeMap<>();
int evjmp, oddjmp;
for(int i = len-1; i>=0; i--)
{
Integer minp... | class Solution {
private:
void tryOddJump(const int idx,
const int val,
std::map<int, int>& visitedNode,
vector<int>& oddJumpsDP,
vector<int>& evenJumpsDP) {
// looking for equal or bigger element and it's going to be smallest p... | /**
* @param {number[]} arr
* @return {number}
*/
var oddEvenJumps = function(arr) {
let result = 0;
const len = arr.length
const map = {} // { value: index }
const memo = new Array(2).fill(null).map(i => new Array(len).fill(false))
// Build a BST to maintain logN search/Insert
function ... | Odd Even Jump |
Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:
Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.
Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.
In other words, we ... | class Solution:
def minInsertions(self, s: str) -> int:
leftbrackets = insertions = 0
i, n = 0, len(s)
while i < n:
if s[i] == '(':
leftbrackets += 1
elif s[i] == ')':
if i == n-1 or s[i+1] != ')': insertions += 1
else:... | class Solution {
public int minInsertions(String s) {
int open=0;
int ans=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('){
open++;
}
else{
if(i+1<s.length() && s.charAt(i+1)==')'){
i++;
... | class Solution {
public:
int minInsertions(string s) {
stack<int> st;
int n = s.size();
int insert = 0;
for(int i = 0; i < n; i++)
{
if(s[i] == '(')
{
if(st.empty())
{
st.push(2);
}
... | var minInsertions = function(s) {
let rightNeeded = 0;
let leftNeeded = 0;
for (const char of s) {
if (char === "(") {
if (rightNeeded % 2 === 0) {
rightNeeded += 2;
} else {
rightNeeded++;
leftNeeded++;
... | Minimum Insertions to Balance a Parentheses String |
Reversing an integer means to reverse all its digits.
For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained.
Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.
&... | class Solution(object):
def isSameAfterReversals(self, num):
# All you have to do is check the Trailing zeros
return num == 0 or num % 10 # num % 10 means num % 10 != 0 | class Solution {
public boolean isSameAfterReversals(int num) {
return (num%10!=0||num<10);
}
} | class Solution {
public:
bool isSameAfterReversals(int num) {
return num == 0 || num % 10 > 0; // All you have to do is check the Trailing zeros
}
}; | /**
* @param {number} num
* @return {boolean}
*/
var isSameAfterReversals = function(num) {
if(num == 0) return true;
if(num % 10 == 0) return false;
return true;
}; | A Number After a Double Reversal |
Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose... | class Solution:
def makeGood(self, s: str) -> str:
while True:
for i in range(len(s)-1):
if s[i].lower() == s[i+1].lower() and (s[i].islower() and s[i+1].isupper() or s[i].isupper() and s[i+1].islower()):
s = s[:i]+s[i+2:]
break
... | class Solution {
public String makeGood(String s) {
char[] res = s.toCharArray();
int i = 0;
for( char n: s.toCharArray())
{
res[i] = n;
if(i>0 && Math.abs((int) res[i-1]- (int) res[i])==32)
{
i-=2;
}
i++;
}
return new String(res, 0, ... | class Solution {
public:
string makeGood(string s) {
stack<char>st;
st.push(s[0]);
string ans="";
for(int i=1;i<s.size();++i){
if(!st.empty() and (st.top()==s[i]+32 or st.top()==s[i]-32)){
cout<<"top :"<<st.top()<<endl;
st.pop();
}
else {
st.push(s[i]);
}
}
while(!st.empty()){
... | var makeGood = function(s) {
const sArr = []
for(let i = 0; i < s.length; i++) {
sArr.push(s[i])
}
const popper = function() {
let counter = 0
for(let i = 0; i < sArr.length; i++) {
if(sArr[i] !== sArr[i + 1]) {
if(sArr[i].toUpperCase() === sAr... | Make The String Great |
Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Example 1:
Input: s = "00110011"
Output: ... | class Solution:
def countBinarySubstrings(self, s: str) -> int:
# previous continuous occurrence, current continuous occurrence
pre_cont_occ, cur_cont_occ = 0, 1
# counter for binary substrings with equal 0s and 1s
counter = 0
# scan each character pair i... | class Solution
{
public int countBinarySubstrings(String s)
{
int i , prevRunLength = 0 , curRunLength = 1 , count = 0 ;
for ( i = 1 ; i < s.length() ; i++ )
{
if( s.charAt(i) == s.charAt( i - 1 ) )
{
curRunLength++;
}
else
... | class Solution {
public:
int countBinarySubstrings(string s) {
int prev=0;
int curr=1;
int sum=0;
for(int i=1;i<s.length();i++){
if(s[i]==s[i-1]){
curr++;
}
else{
sum+= min(prev, curr);
prev=curr;
... | /**
* find all bit switches '01' and '10'.
* From each one expand sideways: i goes left, j goes right
* Until:
* if '01' -> i,j != 0,1
* if '10' -> i,j != 1,0
* and within input boundaries
*/
var countBinarySubstrings = function(s) {
let i = 0;
const n = s.length;
let count = 0;
while (i < n-1) ... | Count Binary Substrings |
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.
You are given a list of strings keyName a... | class Solution:
# 668 ms, 99.52%. Time: O(NlogN). Space: O(N)
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
def is_within_1hr(t1, t2):
h1, m1 = t1.split(":")
h2, m2 = t2.split(":")
if int(h1) + 1 < int(h2): return False
... | class Solution {
public List<String> alertNames(String[] keyName, String[] keyTime) {
Map<String, PriorityQueue<Integer>> map = new HashMap<>();
// for every entry in keyName and keyTime, add that time to a priorityqueue for that name
for(int i=0;i<keyName.length;i++){
PriorityQueue<In... | class Solution {
public:
bool timeDiff(vector<string> timestamp, int index){
int time1 = ((timestamp[index][0]-'0') * 10 + (timestamp[index][1]-'0')) * 60 + ((timestamp[index][3]-'0') * 10 + (timestamp[index][4]-'0'));
int time2 = ((timestamp[index+2][0]-'0') * 10 + (timestamp[index+2][1]-'0')) * 60... | /**
* @param {string[]} keyName
* @param {string[]} keyTime
* @return {string[]}
*/
var alertNames = function(keyName, keyTime) {
// so we don't keep duplicates
const abusers = new Set();
// map: name->times[] (sorted)
const times = {};
for (let i=0; i<keyName.length; i++) {
const name =... | Alert Using Same Key-Card Three or More Times in a One Hour Period |
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :
p[0] = start
p[i] and p[i+1] differ by only one bit in their binary representation.
p[0] and p[2^n -1] must also differ by only one bit in their binary representation.
Example 1:
Input: n... | class Solution:
def circularPermutation(self, n: int, start: int) -> List[int]:
gray_code = [x ^ (x >> 1) for x in range(2 ** n)]
start_i = gray_code.index(start)
return gray_code[start_i:] + gray_code[:start_i] | class Solution {
public List<Integer> circularPermutation(int n, int start) {
List<Integer> l = new ArrayList<Integer>();
int i=0;
int len = (int)Math.pow(2,n);
int[] arr = new int[len];
while(i<len){
arr[i]=(i)^(i/2);
i++;
}
i... | class Solution {
public:
vector<string> get_val(int n)
{
if(n==1)return {"0","1"};
vector<string> v = get_val(n-1);
vector<string> ans;
for(int i = 0;i<v.size();i++)
{
ans.push_back("0" + v[i]);
}
for(int i = v.size()-1;i>=0;i--)
{
... | var circularPermutation = function(n, start) {
const grayCodes = [];
let startIdx = -1;
for (let i = 0; i <= 2**n - 1; i++) {
grayCodes[i] = i ^ (i >> 1);
if (grayCodes[i] == start) startIdx = i;
}
const res = [];
for (let i = 0; i <= 2**n - 1; i++) {
res[i] = grayCo... | Circular Permutation in Binary Representation |
You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:
You should build the array arr which has the following properties:
arr has exactly n integers.
1 <= arr[i] <= m where (0 <= i < n).
After applying the mentioned algor... | class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
@cache
def dp(a,b,c):
if a==n: return c==k
return (b*dp(a+1,b,c) if b>=1 else 0) + sum(dp(a+1,i,c+1) for i in range(b+1,m+1))
return dp(0,0,0)%(10**9+7) | class Solution {
public int numOfArrays(int n, int m, int k) {
int M = (int)1e9+7, ans = 0;
int[][] dp = new int[m+1][k+1]; // maximum value, num of elements seen from left side
for (int i = 1; i <= m; i++){
dp[i][1]=1; // base case
}
for (int i = 2; i <= n; i++)... | class Solution {
public:
int numOfArrays(int n, int m, int k) {
if(m<k)return 0;
int dp[2][m+1][k+1],mod=1e9+7;
memset(dp,0,sizeof(dp));
for(int j=1;j<=m;++j)
dp[0][j][1]=j;
for(int i=1;i<n;++i)
for(int j=1;j<=m;++j)
for(int l=1;l<=min(... | var numOfArrays = function(n, m, k){
let mod=1e9+7,
// dp[i][c][j] the number of arrays of length i that cost c and their max element is j
dp=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>[...Array(m+1)].map(d=>0))),
// prefix[i][k][j] holds the prefix sum of dp[i][k][:j]
prefix=... | Build Array Where You Can Find The Maximum Exactly K Comparisons |
You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1.
You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.
You need to assign each city with an integer value from 1 to... | class Solution:
def maximumImportance(self, n: int, roads: List[List[int]]) -> int:
Arr = [0] * n # i-th city has Arr[i] roads
for A,B in roads:
Arr[A] += 1 # Each road increase the road count
Arr[B] += 1
Arr.sort() # Cities with most road should receive the most sc... | class Solution {
public long maximumImportance(int n, int[][] roads) {
long ans = 0, x = 1;
long degree[] = new long[n];
for(int road[] : roads){
degree[road[0]]++;
degree[road[1]]++;
}
Arrays.sort(degree);
for(long i : degree) ans += i * (x++)... | class Solution {
public:
long long maximumImportance(int n, vector<vector<int>>& roads) {
vector<int>ind(n,0);
for(auto it:roads)
{
ind[it[0]]++;
ind[it[1]]++;
}
priority_queue<long long> pq;
long long val = n,ans=0;
... | var maximumImportance = function(n, roads) {
const connectionCount = Array(n).fill(0)
// Count the connections from each city
// e.g. the 0th city's count will be stored at index zero in the array
for (let [cityTo, cityFrom] of roads) {
connectionCount[cityTo]++
connectionCount[cityFrom... | Maximum Total Importance of Roads |
Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).
Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table.
Example 1:
Input: m = 3, n = 3, k = 5
Output: 3
Explanat... | class Solution:
def numSmaller(self, x, m, n):
res = 0
for i in range(1, m + 1):
res += min(x // i, n)
return res
def findKthNumber(self, m: int, n: int, k: int) -> int:
beg = 1
end = m * n
while beg < end:
mid = (beg + end) // 2
... | class Solution {
public int findKthNumber(int m, int n, int k) {
int lo = 1;
int hi = m * n;
while(lo < hi){
int mid = lo + (hi - lo) / 2;
if(count(mid, m, n) < k){
lo = mid + 1;
} else if(count(mid, m, n) >= k){
... | class Solution {
public:
int findKthNumber(int m, int n, int k) {
int high=m*n ,low=1;
int mid=0, ans=1e9;
while(low<=high)
{
mid=low+(high-low)/2;
int temp=0;
// for each i find the max value ,less than or equal to n , such that
// ... | /**
* @param {number} m
* @param {number} n
* @param {number} k
* @return {number}
*/
var findKthNumber = function(m, n, k) {
// lo always points to a value which is
// not going to be our answer
let lo = 0;
let hi = m * n;
// the loop stops when lo and hi point to two adjascent numbers
// because lo ... | Kth Smallest Number in Multiplication Table |
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
After you sell your stock, you cannot... | class Solution:
def maxProfit(self, prices: List[int]) -> int:
cache = {}
def dfs(i, buying):
if i >= len(prices):
return 0
if (i, buying) in cache:
return cache[(i, buying)]
... | class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[][] dp = new int[n+2][2];
for(int index = n-1; index>=0; index--){
for(int buy = 0; buy<=1; buy++){
int profit = 0;
if(buy == 0){ // buy stocks
... | class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int ans = 0;
vector<int> dp(n, 0);
for (int i = 1; i < n; ++i) {
int max_dp = 0;
for (int j = 0; j < i; ++j) {
dp[i] = max(dp[i], prices[i] - prices[j] + max_dp);
max_dp = max(max_dp, j > ... | /**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let dp = {};
let recursiveProfit = (index,buy) =>{
if(index>=prices.length){
return 0;
}
if(dp[index+'_'+buy]) return dp[index+'_'+buy]
if(buy){
dp[index+'_'+buy] = ... | Best Time to Buy and Sell Stock with Cooldown |
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Implement the MyStack class:
void push(int x) Pushes element x to the top of the stack.
int pop() Removes the element on the top of the stack and r... | class MyStack:
def __init__(self):
self.q1 = deque()
self.q2 = deque()
def push(self, x: int) -> None:
self.q1.append(x)
def pop(self) -> int:
while len(self.q1) > 1:
self.q2.append(self.q1.popleft())
popped_element = self.q1.popleft()
... | class MyStack {
Queue<Integer> queue = null;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
Queue<Integer> tempQueue = new LinkedList<>();
tempQueue.add(x);
while(!queue.isEmpty()){
tempQueue.add(queue.remove());
}
... | class MyStack {
public:
queue<int> q1;
queue<int> q2;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
while(q1.size() !=1){
int temp = q1.front();
q1.pop();
q2.push(temp);
}
int temp = q1.front();
q1.pop(... | var MyStack = function() {
this.stack = [];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.stack.push(x);
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
return this.stack.splice([this.stack.length-1], 1)
};
/**
* @return {number}
*/
M... | Implement Stack using Queues |
Given the root of a binary tree, return the leftmost value in the last row of the tree.
Example 1:
Input: root = [2,1,3]
Output: 1
Example 2:
Input: root = [1,2,3,4,null,5,6,null,null,7]
Output: 7
Constraints:
The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 2... | # 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 findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
res = root.val
stac... | class Solution {
int max = Integer.MIN_VALUE;
int res = -1;
public int findBottomLeftValue(TreeNode root) {
check(root,0);
return res;
}
void check(TreeNode root, int h){
if(root==null)
return;
if(h>max){
max=h;
res = root.val;
... | class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
int ans=root->val;
while(!q.empty()){
int n=q.size();
for(int i=0;i<n;i++){
TreeNode* curr= q.front();
q.pop();
... | var findBottomLeftValue = function(root) {
let arr=[];
let q=[root];
while(q.length!==0){
let current=q.shift();
arr.push(current.val)
if(current.right){
q.push(current.right)
}
if(current.left){
q.push(current.left);
}
}
return... | Find Bottom Left Tree Value |
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7
Output: 4
Example 2:
Input: left = 0, right = 0
Output: 0
Example 3:
Input: left = 1, right = 2147483647
Output: 0
Const... | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
if not left: return 0
i = 0
cur = left
while cur + (cur & -cur) <= right:
cur += cur & -cur
left &= cur
return left | class Solution {
public int rangeBitwiseAnd(int left, int right) {
int count=0;
while(left!=right){
left>>=1;
right>>=1;
count++;
}
return right<<=count;
} | class Solution {
public:
int rangeBitwiseAnd(int left, int right) {
int t=0;
while(left!=right){
left= left>>1;
right= right>>1;
t++;
}
int ans= left;
while(t--){
ans= ans<<1;
}
return ans;
}
}; | var rangeBitwiseAnd = function(left, right) {
const a = left.toString(2);
const b = right.toString(2);
if (a.length !== b.length) {
return 0;
}
let match = 0;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
break;
}
match++;
}
re... | Bitwise AND of Numbers Range |
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4... | class Solution(object):
def minDepth(self, root):
# Base case...
# If the subtree is empty i.e. root is NULL, return depth as 0...
if root is None: return 0
# Initialize the depth of two subtrees...
leftDepth = self.minDepth(root.left)
rightDepth = self.minDepth(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;
* ... | class Solution {
public:
void maxlevel(TreeNode* root,int level,int &ans){
if(!root)
return ;
if(!root->left && !root->right){
ans=min(level,ans);
return ;
}
maxlevel(root->left,level+1,ans);
maxlevel(root->right,level+1,ans);
}
i... | var minDepth = function(root) {
if (!root){
return 0
}
if(root.left && root.right){
return Math.min(minDepth(root.left), minDepth(root.right)) + 1
}
if(root.right){
return minDepth(root.right) + 1
}
if(root.left){
return minDepth(root.left) + 1
}
retur... | Minimum Depth of Binary Tree |
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.
You must write an algorithm that runs in O(n) time and uses O(1) extra space.
Example 1:
Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Example 2:
Input: n = 2
Output: [1,2]
Constraint... | class Solution:
def lexicalOrder(self, n: int) -> List[int]:
result = []
orderDic = {}
for i in range(1, n + 1):
strI = str(i)
level = orderDic
for char in strI:
if char not in level:
level[char] = {}
lev... | class Solution {
private final TrieNode trie = new TrieNode(' ');
class TrieNode{
private Character digit;
private String value;
private boolean isWord;
private Map<Character, TrieNode> children;
TrieNode(Character c){
this.digit = c;
this.isWo... | class Solution {
private:
void dfs(int i, int n, vector<int> &ans){
if(i > n) return;
ans.push_back(i);
for(int j = 0; j< 10; ++j) dfs(i * 10 + j, n, ans);
}
public:
vector<int> lexicalOrder(int n) {
vector<int> ans;
for(int i =1; i<10; ++i) dfs(i, n, ans);
re... | /**
* @param {number} n
* @return {number[]}
*/
var lexicalOrder = function(n) {
const arr = [];
function dfs(baseIndex) {
if (baseIndex * 10 > n) {
return;
}
for(let i = baseIndex * 10; i < baseIndex * 10 + 10 && i <= n; i++) {
arr.push(i);
... | Lexicographical Numbers |
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
 ... | class Solution:
def lengthOfLIS(self, nums: list[int]) -> int:
# Initialize the result
res = []
# Binary search to find the index of the smallest number in result that is greater than or equal to the target
def binarySearch(l, r, target):
nonlocal res
# If... | class Solution {
public int lengthOfLIS(int[] nums) {
ArrayList<Integer> lis = new ArrayList<>();
for(int num:nums){
int size = lis.size();
if(size==0 ||size>0 && num>lis.get(size-1)){
lis.add(num);
}else{
int insertIndex = bs(l... | class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int>dp(n,1);
for(int i=n-2;i>=0;i--){
for(int j=i+1;j<n;j++){
if(nums[j]>nums[i])dp[i]=max(dp[i],1+dp[j]);
}
}
int mx=0;
for(int i=0;i<n;i++... | var lengthOfLIS = function(nums) {
let len = nums.length;
let dp = Array.from({length: len}, v => 1);
for (let i = 1 ; i < len; i++) {
for (let j = 0; j < i; j++) {
if (nums[i] > nums[j] && dp[i] <= dp[j]) {
dp[i] = dp[j] + 1;
}
}
}
return Math.max(...dp);
}; | Longest Increasing Subsequence |
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.
Example 1:
Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6]... | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k==0 or k==1:
return 0
p=1
ini=0
fin=0
n=len(nums)
c=0
while fin<n:
p=p*nums[fin]
while p>=k :
p=p//nums[ini]
... | class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
//if k=0 then ans will always be zero as we have positive integers array only.
if(k==0)
return 0;
int length = 0;
long product = 1;
int i = 0;
int j = 0;
int n = nums.l... | class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int start = 0;
long prod = 1;
int count =0; // count of subarray prod less than k
for(int end =0; end< nums.size(); end++){
prod *= nums[end];
while(prod >= k && start < ... | var numSubarrayProductLessThanK = function(nums, k) {
var used = new Array(nums.length).fill(0);
var l, r, runsum=1;
let ans=0;
l = 0;
r = 0;
while( r < nums.length ) {
if( r < nums.length && runsum * nums[r] >= k ) {
if( r != l )
runsum /= nums[l];
... | Subarray Product Less Than K |
Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Example 1:
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 an... | class Solution:
def countOdds(self, low: int, high: int) -> int:
total_nums = high - low
answer = total_nums // 2
if low % 2 == 1 and high % 2 == 1:
return answer + 1
if low % 2 == 1:
answer = answer + 1
... | class Solution {
public int countOdds(int low, int high) {
if(low%2==0 && high%2==0){
return (high-low)/2;
}
return (high-low)/2+1;
}
} | class Solution {
public:
int countOdds(int low, int high) {
if (low%2 == 0 && high%2 == 0 ){
return (high - low)/2;
}
else{
return (high - low)/2 + 1;
}
}
}; | var countOdds = function(low, high) {
let total = 0;
for (let i = low; i <= high; i++) {
if (i % 2 !== 0) {
total++;
}
}
return total;
}; | Count Odd Numbers in an Interval Range |
There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:
Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).
Paste: You can paste the characters which are copied last time.
Given an integer n, retu... | class Solution:
def minSteps(self, n: int) -> int:
# at every step we can copy or paste
# paste -> we need to know the current clipboard content (count)
# copy -> set clipboard count to current screen count (we should consider it, if the last operation was paste)
memo ... | class Solution {
public int minSteps(int n) {
int rem = n-1, copied = 0, ans = 0, onScreen = 1;
while(rem>0){
if(rem % onScreen == 0){
ans++; // copy operation
copied = onScreen;
}
rem-=copied;
ans++; // past... | class Solution {
public:
//See the solution for this explanation
int byPrimeFactorization(int n) {
if(n == 1)
return 0;
if(n == 2)
return 2;
int factor = 2, ans = 0;
while(n > 1) {
while(n % factor == 0) {
ans += factor;
... | var minSteps = function(n) {
let result = 0;
for (let index = 2; index <= n; index++) {
while (n % index === 0) {
result += index;
n /= index;
}
}
return result;
}; | 2 Keys Keyboard |
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Example 1:
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]
Example 2:
Input: root = [1,2,3]
Output: [1,3]
Constraints:
The number of nodes in the tree will be in the range [0, 104].
-231 ... | class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
ans=[]
q=[]
q.append(root)
while q:
s=len(q)
t=[]
for i in range(s):
... | /**
* 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 Solutio... | class Solution {
public:
vector<int>res;
vector<int> largestValues(TreeNode* root) {
if(!root) return {};
if(!root->left && !root->right) return {root->val};
TreeNode*temp;
int mx = INT_MIN;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
... | var largestValues = function(root) {
if(!root) return [];
const op = [];
const Q = [[root, 1]];
while(Q.length) {
const [r, l] = Q.shift();
if(op.length < l) op.push(-Infinity);
op[l-1] = Math.max(op[l-1], r.val);
if(r.left) Q.push([r.left, l + 1]);... | Find Largest Value in Each Tree Row |
You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.
The MKAverage can be calculated using these steps:
If the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwis... | from sortedcontainers import SortedList
class MKAverage:
MAX_NUM = 10 ** 5
def __init__(self, m: int, k: int):
self.m = m
self.k = k
# sorted list
self.sl = SortedList([0] * m)
# sum of k smallest elements
self.sum_k = 0
# sum of m - k smallest ele... | class MKAverage {
class Node implements Comparable<Node> {
int val;
int time;
Node(int val, int time) {
this.val = val;
this.time = time;
}
@Override
public int compareTo(Node other) {
return (this.val != other.val... | /*
Time: addElement: O(logm) | calculateMKAverage: O(1)
Space: O(m)
Tag: TreeMap, Sorting, Queue
Difficulty: H
*/
class MKAverage {
map<int, int> left, middle, right;
queue<int> q;
int sizeofLeft, sizeofMiddle, sizeofRight;
int k;
long long mkSum;
int m;
void addToSet1(int... | class ArraySegTree{
// Array to perfrom operations on, range query operation, PointUpdate operation
constructor(A,op=(a,b)=>a+b,upOp=(a,b)=>a+b,opSentinel=0){
this.n=A.length,this.t=[...Array(4*this.n+1)],this.op=op,this.upOp=upOp,this.opSentinel=opSentinel
//root's idx =1
this.build(A,1... | Finding MK Average |
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Ou... | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# transpose
size = len(matrix)
for i in range(size):
for j in range(i+1, size):
matrix[j][i],matrix[i][... | class Solution {
public void swap(int[][] matrix, int n1, int m1, int n2, int m2) {
int a = matrix[n1][m1];
int temp = matrix[n2][m2];
matrix[n2][m2] = a;
matrix[n1][m1] = temp;
}
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < ... | class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int row = matrix.size();
for(int i=0;i<row; i++){
for(int j=0; j<=i;j++){
swap(matrix[i][j], matrix[j][i]);
}
}
for(int i=0;i<row;i++){
reverse(matrix[i].begin(), m... | /**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
let m = matrix.length;
let n = matrix[0].length;
for (let i = m - 1; i >= 0; i--) {
for (let j = 0; j < m; j++) {
matrix[j].push(matrix[i].... | Rotate Image |
A transaction is possibly invalid if:
the amount exceeds $1000, or;
if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.
You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in m... | class Transaction:
def __init__(self, name, time, amount, city):
self.name = name
self.time = int(time)
self.amount = int(amount)
self.city = city
from collections import defaultdict
class Solution:
def invalidTransactions(self, transactions):
transactions = [Transaction... | class Solution {
public List<String> invalidTransactions(String[] transactions) {
Map<String, List<Transaction>> nameToTransaction = new HashMap<>();
for (int i = 0; i < transactions.length; i++) {
Transaction t = new Transaction(transactions[i], i);
nameToTransaction.putIfAbsent(t.name, new Array... | class Solution {
public:
/*
this question is absolutely frustrating 🙂
*/
/*
method to split string
*/
vector<string> split(string s){
string t="";
vector<string> v;
for(int i=0;i<s.length();i++){
if(s[i]==','){
v.push_back(t);
... | var invalidTransactions = function(transactions) {
const invalid = new Uint8Array(transactions.length).fill(false);
for(let i = 0; i < transactions.length; i++){
const [name, time, amount, city] = transactions[i].split(',');
if(+amount > 1000) invalid[i] = true;
for(let j = i + 1; j <... | Invalid Transactions |
Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.
Note:
The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
A subtree of root is a tree consisting of root and all of ... | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
def calculate_average(root):
if root:
self.summ+=root.val
self.nodecount+=1
calculate_average(root.left)
calculate_average(root.right)
... | class Solution {
int res = 0;
public int averageOfSubtree(TreeNode root) {
dfs(root);
return res;
}
private int[] dfs(TreeNode node) {
if(node == null) {
return new int[] {0,0};
}
int[] left = dfs(node.left);
int[] right = dfs(nod... | class Solution {
public:
pair<int,int> func(TreeNode* root,int &ans){
if(!root)return {0,0};
auto p1=func(root->left,ans);
auto p2=func(root->right,ans);
int avg=(root->val+p1.first+p2.first)/(p1.second+p2.second+1);
if(avg==root->val)ans++;
return {root->val+p1.first... | var averageOfSubtree = function(root) {
let result = 0;
const traverse = node => {
if (!node) return [0, 0];
const [leftSum, leftCount] = traverse(node.left);
const [rightSum, rightCount] = traverse(node.right);
const currSum = node.val + leftSum + rightSum... | Count Nodes Equal to Average of Subtree |
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
At each iteration, insertion sort removes one element from... | /**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function insertionSortList... | class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode cur = head;
ListNode temp = new ListNode(-5001);
ListNode prev = temp;
while(cur != null){
ListNode nxt = cur.next;
if(prev.val >= cur.val)
prev = temp;
wh... | class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode *prev=head,*cur=head->next;
while(cur){
ListNode *tmp=head,*pt=NULL;
while(tmp!=cur and tmp->val < cur->val){
pt=tmp;
tmp=tmp->next;
}
if(tm... | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var insertionSortList = function(head) {
let ptr = head;
while(ptr.n... | Insertion Sort List |
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "cbaeba... | from collections import Counter
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
l='abcdefghijklmnopqrstuvwxyz'
if len(p)>len(s):
return []
d={}
for x in l:
d[x]=0
d1=dict(d)
d2=dict(d)
for x in range(len(p)):
... | class Solution {
public List<Integer> findAnagrams(String s, String p) {
int fullMatchCount = p.length();
Map<Character, Integer> anagramMap = new HashMap<>();
for (Character c : p.toCharArray())
anagramMap.put(c, anagramMap.getOrDefault(c, 0) + 1);
... | //easy to understand
class Solution {
public:
bool allZeros(vector<int> &count) {
for (int i = 0; i < 26; i++) {
if (count[i] != 0)
return false;
}
return true;
}
vector<int> findAnagrams(string s, string p) {
string s1 = p, s2 = s;
int n ... | var findAnagrams = function(s, p) {
function compareMaps(map1, map2) {
var testVal;
if (map1.size !== map2.size) {
return false;
}
for (var [key, val] of map1) {
testVal = map2.get(key);
// in cases of an undefined value, make sure the key
// actually exists on the o... | Find All Anagrams in a String |
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input: matrix = [[1,... | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
left=0
right=len(matrix)-1
while left <= right:
mid=(left+right)//2
if matrix[mid][0] < target:
left = mid+1
elif matrix[mid][0] >target:
... | class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (target < matrix[0][0]) {
return false;
}
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][0] > target | i == matrix.length - 1) {
if (matrix[i][0] > target) {
... | class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for(int i = 0; i < matrix.size(); i ++) {
if(matrix[i][0] > target) return false;
for(int j = 0; j < matrix[i].size(); j ++) {
if(matrix[i][j] == target) return true;
... | var searchMatrix = function(matrix, target) {
let matCopy = [...matrix];
let leftIndex = 0;
let rightIndex = matrix.length - 1;
let mid = Math.ceil((matrix.length - 1) / 2);
let eachMatrixLength = matrix[0].length;
if (matrix[mid].includes(target) === true) {
return true;
} else... | Search a 2D Matrix |
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a pe... | class ThroneInheritance:
def __init__(self, kingName: str):
# Taking kingName as root
self.root = kingName
# notDead will hold all the people who are alive and their level number
self.alive = {}
self.alive[kingName] = 0
# hold edges existing in our graph
se... | class Tree{
List<Tree>child;
String name;
public Tree(String name,List<Tree>child){
this.name=name;
this.child=child;
}
}
class ThroneInheritance {
private Set<String>death;
private Tree tree;
private Map<String,Tree>addtoTree;
public ThroneInheritance(String kingName) {
... | class ThroneInheritance {
public:
ThroneInheritance(string kingName) {
curr_king = kingName;
}
void birth(string parentName, string childName) {
children[parentName].push_back(childName);
}
void death(string name) {
dead.insert(name);
}
void rec(string ... | var bloodList = function(name, parent = null) {
return {
name,
children: []
};
}
var ThroneInheritance = function(kingName) {
this.nameMap = new Map();
this.nameMap.set(kingName, bloodList(kingName));
this.king = kingName;
this.deadList = new Set();
};
/**
* @param {string} pa... | Throne Inheritance |
Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j]). If it cannot be done, then return the same array.
Example 1:
I... | class Solution:
def find_max(self, i, a, n):
maxs = i+1
for j in range(n-1, i, -1):
# if only j is greater than max and smaller than first descending element
if(a[maxs] <= a[j] and a[j] < a[i]):
maxs = j
# Swap
a[i], a[maxs] = a[maxs], a[i]
... | class Solution {
public int[] prevPermOpt1(int[] arr) {
int n=arr.length;
int small=arr[n-1];
int prev=arr[n-1];
for(int i=n-2;i>=0;i--){
if(arr[i]<=prev){
prev=arr[i];
}
else{
int indte=i;
int te=0;
... | class Solution {
public:
vector<int> prevPermOpt1(vector<int>& arr) {
int i, p, mn = -1;
for(i=arr.size() - 2; i>=0; i--) {
if(arr[i] > arr[i + 1]) break;
}
if(i == -1) return arr;
for(int j=i + 1; j<arr.size(); j++) {
if(arr[j] > mn && arr[j] < arr[i... | var prevPermOpt1 = function(arr) {
const n = arr.length;
let i = n - 1;
while (i > 0 && arr[i] >= arr[i - 1]) i--;
if (i === 0) return arr;
const swapIndex = i - 1;
const swapDigit = arr[swapIndex];
let maxIndex = i;
i = n - 1;
while (swapIndex < i) {
con... | Previous Permutation With One Swap |
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
Every adjacent pair of words differs by a single letter.
Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be i... | class Solution:
WILDCARD = "."
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
"""
Given a wordlist, we perform BFS traversal to generate a word tree where
every node points to its parent node.
Then we perform a DFS traversal on thi... | class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
Set<String> dict = new HashSet(wordList);
if( !dict.contains(endWord) )
return new ArrayList();
// adjacent words for each word
Map<String,List<Strin... | // BFS gives TLE if we store path while traversing because whenever we find a better visit time for a word, we have to clear/make a new path vector everytime.
// The idea is to first use BFS to search from beginWord to endWord and generate the word-to-children mapping at the same time.
// Then, use DFS (backtracking)... | const isMatch = (currWord, nextWord) => {
let mismatch = 0;
for(let i = 0; i < nextWord.length; i += 1) {
if(nextWord[i] !== currWord[i]) {
mismatch += 1;
}
}
return mismatch === 1;
}
const getNextWords = (lastRung, dictionary) => {
const nextWords = [];
for(const w... | Word Ladder II |
Given the head of a singly linked list, return true if it is a palindrome.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
The number of nodes in the list is in the range [1, 105].
0 <= Node.val <= 9
Follow up: Could you d... | class Solution:
def isPalindrome(self, head: "Optional[ListNode]") -> bool:
if head.next == None: return True #if only 1 element, it's always a palindrome
forward = head
first_half = []
fast = head
while (fast != None and fast.next != None):
first_half.append(for... | class Solution {
public boolean isPalindrome(ListNode head) {
ListNode mid = getMiddle(head);
ListNode headSecond = reverse(mid);
ListNode reverseHead = headSecond;
while(head != null && headSecond != null){
if(head.val != headSecond.val){
... | class Solution {
public:
ListNode* reverse(ListNode* head)
{
ListNode* prev=nullptr;
while(head)
{
ListNode* current=head->next;
head->next=prev;
prev=head;
head=current;
}
return prev;
}
bool isPalindrome(ListNode* ... | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function(head) {
let slow = head;
let fast = head;
// Movin... | Palindrome Linked List |
On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, ... | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
# Checking for possible case to the right of Rook
def right_position(n,i):
List = i[0:n][::-1] # taking list to the right of rook
pIndex,bIndex = -1,-1
if 'p' in List: # Checking if 'p' in list ... | class Solution {
public int numRookCaptures(char[][] board) {
int ans = 0;
int row = 0;
int col = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == 'R') {
row = i;
col = j;
... | class Solution {
public:
int numRookCaptures(vector<vector<char>>& board) {
int res=0;
int p=-1,q=-1;
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board[0].size();j++)
{
if(board[i][j]=='R') // storing position of R
{
... | var numRookCaptures = function(board) {
const r=board.length;
const c=board[0].length;
let res=0
const dir=[[0,1],[0,-1],[1,0],[-1,0]]; // all the 4 possible directions
let rook=[];
// finding the rook's position
for(let i=0;i<r;i++){
for(let j=0;j<c;j++){
if(board[i][j... | Available Captures for Rook |
Given the root of a Binary Search Tree (BST), return the minimum 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... | # class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
temp1=float(inf)
from coll... | /**
* 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;
* ... | class Solution {
int minDiff=INT_MAX,prev=INT_MAX;
public:
void inorder(TreeNode* p){
if(p==NULL) return;
inorder(p->left);
minDiff=min(minDiff,abs(p->val-prev));
prev=p->val;
inorder(p->right);
}
int minDiffInBST(TreeNode* root) {
inorder(root);
r... | /**
* @param {TreeNode} root
* @return {number}
*/
var minDiffInBST = function(root) {
let arr = [];
const helper = (node) => {
if (node) {
helper(node.left);
arr.push(node.val);
helper(node.right);
}
}
helper(root);
let min = Infinity;
for (let i = 0; i < arr.length - 1; i++) {
con... | Minimum Distance Between BST Nodes |
Alice and Bob have an undirected graph of n nodes and three types of edges:
Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can be traversed by both Alice and Bob.
Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nod... | class DSUF:
def __init__(self, n):
self.arr = [-1] * n
def find(self, node):
p = self.arr[node]
if p == -1:
return node
self.arr[node] = self.find(p)
return self.arr[node]
def union(self, a, b):
aP = self.find(a)
bP = self.find(b)
i... | class Solution {
public int maxNumEdgesToRemove(int n, int[][] edges)
{
Arrays.sort(edges, (a, b)->{
return b[0]-a[0];
});//giving the priority to third type of edge or the edge which Bob and Alice both can access
//1-based indexing of nodes
int []parentAli... | class Solution {
public:
vector < int > Ar , Ap , Br , Bp; // alice and bob parent and rank arrays
static bool cmp(vector < int > & a , vector < int > & b){
return a[0] > b[0];
}
// lets create the alice graph first
// find function for finding the parent nodes
int find1(int x){
if(x ... | // A common disjoint set class
function DS(n) {
var root = [...new Array(n + 1).keys()];
var rank = new Array(n + 1).fill(0);
this.find = function(v) {
if (root[v] !== v) root[v] = this.find(root[v]);
return root[v];
}
this.union = function (i, j) {
var [a, b] = [this.find(i)... | Remove Max Number of Edges to Keep Graph Fully Traversable |
Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.
After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.
Example 1:
Input: n = 34, k = 6
Output: 9
Explanation: 34 (base 10) expr... | class Solution:
def sumBase(self, n: int, k: int) -> int:
cnt = 0
while n:
cnt += (n % k)
n //= k
print(cnt)
return cnt | class Solution {
public int sumBase(int n, int k) {
int res = 0;
for (; n > 0; n /= k)
res += n % k;
return res;
}
} | class Solution {
public:
int sumBase(int n, int k) {
int sum=0;
while(n!=0) sum+=n%k,n=n/k;
return sum;
}
}; | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var sumBase = function(n, k) {
return n.toString(k).split("").reduce((acc, cur) => +acc + +cur)
}; | Sum of Digits in Base K |
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
The number of the nodes in the tree is in the range [0,... | from typing import List, Optional
class Solution:
"""
Time: O(n)
"""
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
postorder = []
stack = [root]
while stack:
node = stack.pop()
postorder.append(node.val)
if node.left is not None:
stack... | /**
* 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 Solutio... | class Solution {
void solve(TreeNode *root, vector<int> &ans){
if(root == NULL) return;
solve(root->left, ans);
solve(root->right, ans);
ans.push_back(root->val);
}
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
solve(root, ans);
... | class Pair{
constructor(node, state){
this.node = node;
this.state = state;
}
}
var postorderTraversal = function(root) {
let ans = [];
let st = []; // stack
root != null && st.push(new Pair(root, 1));
while(st.length > 0){
let top = st[st.length - 1];
if(top.st... | Binary Tree Postorder Traversal |
You are given an n x n binary matrix grid where 1 represents land and 0 represents water.
An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.
You may change 0's to 1's to connect the two islands to form one island.
Return the smallest number of... | class Solution:
def shortestBridge(self, grid):
m, n = len(grid), len(grid[0])
start_i, start_j = next((i, j) for i in range(m) for j in range(n) if grid[i][j])
stack = [(start_i, start_j)]
visited = set(stack)
while stack:
i, j = stack.pop()
... | class Solution {
private static int[][] dirs={{1,0},{-1,0},{0,1},{0,-1}};
public int shortestBridge(int[][] grid) {
boolean[][] visited=new boolean[grid.length][grid[0].length];
LinkedList<Pair> queue=new LinkedList<Pair>();
boolean found=false;
for(int i=0;i<grid.length && !foun... | class Solution {
public:
void findOneIsland(vector<vector<int>>& grid, int i, int j, queue<pair<int, int>>& q){
if(i<0 || j<0 || i==grid.size() || j==grid.size() || grid[i][j]!=1)
return;
grid[i][j] = 2;
q.push({i,j});
findOneIsland(grid, i, j-1, q);
findOneIslan... | /**
* @param {number[][]} grid
* @return {number}
*/
const DIR = [
[0,1],
[0,-1],
[1,0],
[-1,0]
];
var shortestBridge = function(grid) {
const que = [];
const ROWS = grid.length;
const COLS = grid[0].length;
// find first insland
outer:
for(let row=0; row<ROWS; row++) {
... | Shortest Bridge |
You are given an integer array nums with the following properties:
nums.length == 2 * n.
nums contains n + 1 unique elements.
Exactly one element of nums is repeated n times.
Return the element that is repeated n times.
Example 1:
Input: nums = [1,2,3,3]
Output: 3
Example 2:
Input: nums = [2,1,2,5,3,2]
O... | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
return Counter(nums).most_common(1)[0][0] | class Solution {
public int repeatedNTimes(int[] nums) {
int count = 0;
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] == nums[j])
count = nums[j];
}
}
return count;
}
} | class Solution {
public:
int repeatedNTimes(vector<int>& nums) {
unordered_map<int, int> mp;
for(auto it : nums) mp[it]++;
int n;
for(auto it : mp) {
if(it.second == nums.size() / 2) {
n = it.first;
break;
}
}
re... | var repeatedNTimes = function(nums) {
// loop through the array and then as we go over every num we filter that number and get the length. If the length is equal to 1 that is not the element so we continue if its not equal to one its the element we want and we just return that element.
for (let num of nums) {
... | N-Repeated Element in Size 2N Array |
The width of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.
A subsequence is a sequence that can be derived fro... | class Solution:
def sumSubseqWidths(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
M = 10**9+7
res = 0
le = 1
re = pow(2, n-1, M)
#by Fermat's Little Thm
#inverse of 2 modulo M
inv = pow(2, M-2, M)
for num in nums:
... | class Solution {
public int sumSubseqWidths(int[] nums) {
int MOD = (int)1e9 + 7;
Arrays.sort(nums);
long ans = 0;
long p = 1;
for(int i = 0; i < nums.length; i++){
ans = (ans + p * nums[i] - p * nums[nums.length - 1 - i]) % MOD;
p = (p * 2) % MOD;
... | class Solution {
public:
int sumSubseqWidths(vector<int>& nums) {
vector < long long > pow(nums.size() );
pow[0] = 1;
for(int i = 1 ; i<nums.size(); i++){
pow[i] = pow[i-1] * 2 % 1000000007;
}
sort(nums.begin() , nums.end());
long long ans = 0 ; ... | var sumSubseqWidths = function(nums) {
const mod = 1000000007;
nums.sort((a, b) => a - b), total = 0, power = 1;
for(let i = 0; i < nums.length; i++) {
total = (total + nums[i] * power) % mod;
power = (power * 2) % mod;
}
power = 1;
for(let i = nums.length - 1; i >= 0; i--) {
... | Sum of Subsequence Widths |
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","... | class Solution(object):
def reverseString(self, s):
for i in range(len(s)):
s.insert(i,s.pop())
return s | class Solution {
public void reverseString(char[] s) {
int start = 0, end = s.length-1;
while(start < end) {
char temp = s[end];
s[end] = s[start];
s[start] = temp;
start++;
end--;
}
}
} | class Solution {
public:
void reverseString(vector<char>& s) {
int i = -1, j = s.size();
while (++i < --j){
//Instead of using temp we can do the following
s[i] = s[j] + s[i];
s[j] = s[i] - s[j];
s[i] = s[i] - s[j];
}
}
}; | var reverseString = function(s) {
for(let i = 0 ; i < s.length / 2 ; i++){
[s[i], s[s.length - i - 1]] = [s[s.length - i - 1], s[i]]
}
return s;
}; | Reverse String |
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
Example 1:
Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.
Example 2:
Input: date = "2019-02-10"
Output: 41
Constraints:
date.le... | class Solution:
def dayOfYear(self, date: str) -> int:
d={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
year=int(date[:4])
if year%4==0:
if year%100==0:
if year%400==0:
d[2]=29
else:
d[2]=29
... | class Solution {
public int dayOfYear(String date) {
int days = 0;
int[] arr = {31,28,31,30,31,30,31,31,30,31,30,31};
String[] year = date.split("-");
int y = Integer.valueOf(year[0]);
int month = Integer.valueOf(year[1]);
int day = Integer.valueOf(year[2]);
b... | class Solution {
public:
bool leapyear(int year){
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
int dayOfYear(string date) {
vector<int> v;
int ans = 0;
int n = date.length();
for (int i = 0; i < n; i++) {
if (date[i] >= '0' &&... | var dayOfYear = function(date) {
let dat2 = new Date(date)
let dat1 = new Date(dat2.getFullYear(),00,00)
let totalTime = dat2 - dat1
return Math.floor(totalTime/1000/60/60/24)
}; | Day of the Year |
There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right ... | class Solution:
def pushDominoes(self, dom: str) -> str:
from collections import deque
n = len(dom)
d = set()
q = deque()
arr = [0 for i in range(n)]
for i in range(n):
if dom[i] == "L":
arr[i] = -1
d.add(i)
... | // Time complexity: O(N)
// Space complexity: O(N), where N is the length of input string
class Solution {
public String pushDominoes(String dominoes) {
// ask whether dominoes could be null
final int N = dominoes.length();
if (N <= 1) return dominoes;
char[] res = dominoes.toCharArr... | class Solution {
public:
string pushDominoes(string dominoes) {
#define SET(ch, arr) \
if (dominoes[i] == ch) { count = 1; prev = ch; } \
else if (dominoes[i] != '.') prev = dominoes[i]; \
if (prev == ch && dominoes[i] == '.') arr[i] = count++;
... | /**
* @param {string} dominoes
* @return {string}
*/
var pushDominoes = function(dominoes) {
let len = dominoes.length;
let fall = [];
let force = 0;
let answer = "";
// Traverse from left to right. Focus on the dominoes falling to the right
for (let i = 0; i < len; i++) {
i... | Push Dominoes |
You are given an m x n integer array grid where grid[i][j] could be:
1 representing the starting square. There is exactly one starting square.
2 representing the ending square. There is exactly one ending square.
0 representing empty squares we can walk over.
-1 representing obstacles that we cannot walk over.
... | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
ans, empty = 0, 1
def dfs(grid: List[List[int]], row: int, col: int, count: int, visited) -> None:
if row >= len(grid) or col >= len(grid[0]) or row < 0 or col < 0 or grid[row][col] == -1:
re... | class Solution {
int walk = 0;
public int uniquePathsIII(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0) {
walk++;
}
}... | class Solution {
public:
int dfs(vector<vector<int>>&grid,int x,int y,int zero){
// Base Condition
if(x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || grid[x][y] == -1){
return 0;
}
if(grid[x][y] == 2){
return zero == -1 ? 1 : 0; // Why zero = -1, ... | // 980. Unique Paths III
var uniquePathsIII = function(grid) {
const M = grid.length; // grid height
const N = grid[0].length; // grid width
let result = 0; // final result
let startY = 0, startX = 0; // starting point coordinates
let finalY = 0, finalX = 0; // endpoint coordinates
let empty = 0... | Unique Paths III |
A wonderful string is a string where at most one letter appears an odd number of times.
For example, "ccjjc" and "abab" are wonderful, but "ab" is not.
Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the... | class Solution:
def wonderfulSubstrings(self, word: str) -> int:
cnt, res, mask = [1] + [0] * 1023, 0, 0
for ch in word:
mask ^= 1 << (ord(ch) - ord('a'))
res += cnt[mask]
for n in range(10):
res += cnt[mask ^ 1 << n];
cnt[mask] += 1
... | class Solution {
public long wonderfulSubstrings(String word) {
int n = word.length();
long count = 0;
long[] freq = new long[(1 << 10) + 1]; // Since we have to take only 2^10 possibilies, we can avoid an HashMap
freq[0] = 1;
int res = 0; // initialize the ... | class Solution {
public:
long long wonderfulSubstrings(string word) {
int n=word.length();
int mask=0;
unordered_map<int,int>m;
m[0]++;
long long int ans=0;
for(int i=0;i<n;i++){
mask = mask^(1<<(word[i]-'a'));
int temp=mask;
int j=... | /**
* @param {string} word
* @return {number}
*/
var wonderfulSubstrings = function(word) {
let hashMap={},ans=0,binaryRepresentation=0,t,pos,number,oneBitToggled;
hashMap[0]=1;
for(let i=0;i<word.length;i++){
pos = word[i].charCodeAt(0)-"a".charCodeAt(0);//Let's use position 0 for a, 1 for b ...... | Number of Wonderful Substrings |
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraint... | class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 1:
return [[nums[0]]]
res = self.permuteUnique(nums[1:])
for i in range(len(res)-1, -1 , -1):
j = 0
... | class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
boolean used[] = new boolean[nums.length];
permutationsFinder(nums,ans,new ArrayList<>(),used);
return ans;
}
... | class Solution {
public:
void fun(vector<int>& nums, vector<vector<int>>&ans,int i)
{
if(i==nums.size())
{
ans.push_back(nums);
return;
}
int freq[21]={0};
for(int j=i;j<nums.size();j++)
{
if(freq[nums[j]+10]==0)
{
... | var permuteUnique = function(nums) {
const answer = []
function perm (pos, array) {
if (pos >= array.length) {
answer.push(array)
}
const setObject = new Set()
for (let index=pos; index<array.length; index++) {
if (setObject.has(array[index])) {
... | Permutations II |
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
... | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
last_occ = {}
stack = []
visited = set()
for i in range(len(s)):
last_occ[s[i]] = i
for i in range(len(s)):
if s[i] not in visited:
while (stack and stack[-1] > s[i] and last_occ[stack[-1]] > i):
visited.remove(sta... | class Solution {
public String removeDuplicateLetters(String s) {
int[] lastIndex = new int[26];
for (int i = 0; i < s.length(); i++){
lastIndex[s.charAt(i) - 'a'] = i; // track the lastIndex of character presence
}
boolean[] seen = new boolean[26]; // keep track... | class Solution {
public:
string removeDuplicateLetters(string s) {
int len = s.size();
string res = "";
unordered_map<char, int> M;
unordered_map<char, bool> V;
stack<int> S;
for (auto c : s) {
if (M.find(c) == M.end()) M[c] = 1;
else ... | var removeDuplicateLetters = function(s) {
let sset = [...new Set(s)]
if(Math.min(sset) == sset[0]) return [...sset].join('');
else {
sset.sort();
return [...sset].join('');
}
}; | Remove Duplicate Letters |
Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.
The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).
Example 1:
Inpu... | # 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 findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
def dfs(root):
... | class Solution {
public int[] findFrequentTreeSum(TreeNode root) {
HashMap<Integer,Integer> map=new HashMap<>();
int sum=sum(root,map);
int max=0;
int count=0;
for(Integer key:map.keySet()){
max=Math.max(max,map.get(key));
}
for(Integer key:map.k... | class Solution {
private:
unordered_map<int, int> m;
int maxi = 0;
int f(TreeNode* root){
if(!root) return 0;
int l = f(root->left);
int r = f(root->right);
int sum = root->val + l + r;
m[sum]++;
maxi = max(maxi, m[sum]);
return sum;
}
public:
... | var findFrequentTreeSum = function(root) {
const hash = new Map();
const result = [];
let max = 0;
const dfs = (node = root) => {
if (!node) return 0;
const { left, right, val } = node;
const sum = val + dfs(left) + dfs(right);
const count = hash.get(sum) ?? 0;
hash.set(sum, count + 1);
max = Math.max(m... | Most Frequent Subtree Sum |
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th... | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
L = lcm(p,q)
if (L//q)%2 == 0:
return 2
return (L//p)%2 | class Solution {
public int mirrorReflection(int p, int q) {
while (p % 2 == 0 && q % 2 == 0){
p >>= 1; q >>= 1;
}
return 1 - p % 2 + q % 2;
}
}; | class Solution {
public:
int mirrorReflection(int p, int q) {
while (p % 2 == 0 && q % 2 == 0){
p/=2;
q/=2;
}
return 1 - p % 2 + q % 2;
}
}; | // Time complexity: O(log (min(p,q))
// Space complexity: O(1)
var mirrorReflection = function(p, q) {
let ext = q, ref = p;
while (ext % 2 == 0 && ref % 2 == 0) {
ext /= 2;
ref /= 2;
}
if (ext % 2 == 0 && ref % 2 == 1) return 0;
if (ext % 2 == 1 && ref % 2 == 1) return 1;
if (ext % 2 == 1 && ref % 2 == ... | Mirror Reflection |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.