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 containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid par... | class Solution:
def longestValidParentheses(self, s: str) -> int:
maxi = 0
stack = [-1]
for i in range(len(s)) :
if s[i] == "(" : stack.append(i)
else :
stack.pop()
if len(stack) == 0 : stack.append(i)
else : maxi = ma... | class Solution {
public int longestValidParentheses(String s) {
int i=0;
int len=0;
while(i<s.length()){
int j=i;
int open=0;
int closed=0;
while(j<s.length()){
char ch = s.charAt(j);
if(ch=='(') open++;
... | class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length(), i = 0, ans = 0, k = 0;
for(int j = 0; j < n; j++) {
if(s[j] == '(') k++;
else if(s[j] == ')') {
k--;
if(k == 0)
ans = max(ans, j - i + 1);
... | var longestValidParentheses = function(s) {
let indexStack=[-1]
let characterStack=[];
let maxLength=0;
for(let i=0;i<s.length;i++){
if(s[i]=='('){
indexStack.push(i);
characterStack.push(s[i]);
}else{
if(characterStack[characterStack.length-1]=='('){
... | Longest Valid Parentheses |
Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example ... | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
solution = set()
trie = self.make_trie(words)
visited = set()
for i in range(len(board)):
for j in range(len(board[0])):
self.dfs(i,j,board,trie,visited,"",solution... | class Solution {
class TrieNode {
Map<Character, TrieNode> children = new HashMap();
boolean word = false;
public TrieNode() {}
}
int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};
public List<String> findWords(char[][] board, String[] words) {
Set<String> r... | class Solution {
public:
vector<string> result;
struct Trie {
Trie *child[26];
bool isEndOfWord;
string str;
Trie(){
isEndOfWord = false;
str = "";
for(int i=0; i<26; i++)
child[i] = NULL;
}
};
Trie *root = ne... | const buildTrie = (words) => {
const trie = {};
const addToTrie = (word, index = 0, node = trie) => {
const char = word[index];
if(!node[char]) {
node[char] = {};
}
if(index === word.length - 1) {
node[char].word = word;
return word;
}... | Word Search II |
Given an integer n, return the number of prime numbers that are strictly less than n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints:
0 <= n <= 5... | class Solution:
def countPrimes(self, n: int) -> int:
# Prerequisite:
# What is prime number. What are they just the starting.
truth = [True]*n # making a list of lenght n. And keep all the values as True.
if n<2: # as 0 & 1 are not prime numbers.
return 0
... | class Solution {
public int countPrimes(int n) {
boolean check[]=new boolean[n];int count=0;
for(int i=2;i<n;i++){
if(check[i]==false){
count++;
for(int j=i;j<n;j+=i){
check[j]=true;
}
}
}
retur... | class Solution {
public:
int countPrimes(int n) {
if(n == 0 || n == 1) return 0;
vector<bool>prime(n,true);
for(int i = 2; i*i < n; i++){
if(prime[i]){
for(int j = i*i; j < n; j += i){
prime[j] = false;
}
}
}... | function makeSieve(n) {
let arr = new Array(n+1)
arr[0] = false;
arr[1] = false;
arr.fill(true,2,arr.length);
for( let i = 2; i*i<n; i++) {
if(arr[i] === true) {
for( let j = i*i ; j<=n ;j+=i){
arr[j] = false;
}
}
}
let count = 0;
... | Count Primes |
You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit d, the entire current tape is repeatedly written d - 1 mo... | class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
idx = {}
acclens = [0]
prevd = 1
j = 0
for i, c in enumerate(S + '1'):
if c.isalpha():
idx[acclens[-1] * prevd + j] = i
j += 1
else:
acclens... | class Solution {
public String decodeAtIndex(String s, int k) {
long sz = 0;
for (char ch : s.toCharArray()){ // total length
sz = Character.isDigit(ch)? sz * (ch - '0') : ++sz;
}
--k; // make it 0 index based.
for (int i = s.length() - 1; true; i--){
... | class Solution {
public:
string decodeAtIndex(string s, int k) {
k--;
struct op { string s; size_t mult; size_t total; };
vector<op> v;
size_t total = 0;
for (auto c : s) {
if (isalpha(c)) {
if (v.empty() || v.back().mult > 1)
v... | var decodeAtIndex = function(s, k) {
let len=0;
let isDigit=false
for(let v of s){
if(v>='0'&&v<='9'){
len*=+v
isDigit=true
}else{
len++
if(len===k&&!isDigit){
return s[k-1]
}
}
}
for(let i=s.length... | Decoded String at Index |
Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.
You are given an array of strings words and another array of query strings queries. F... | class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
def _f(s):
d = Counter(s)
d =dict(sorted(d.items(), key=lambda item: item[0]))
for x in d:
return d[x]
freq = []
for w in words:
... | class Solution {
public int[] numSmallerByFrequency(String[] queries, String[] words) {
int[] ans = new int[queries.length];
int[] freq = new int[words.length];
for (int i = 0; i < words.length; i++) {
freq[i] = freqOfSmallest(words[i]);
}
Arrays.sort(freq);
... | class Solution {
private:
int countFreq(const string &s) {
char c = *min_element(begin(s), end(s));
return count(begin(s), end(s), c);
}
public:
vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {
vector<int> freqs(11, 0);
for (const auto &word... | /**
* @param {string[]} queries
* @param {string[]} words
* @return {number[]}
*/
var numSmallerByFrequency = function(queries, words) {
let res=[]
queries=queries.map(q=>countFrequency(q))//[3,2]
words=words.map(w=>countFrequency(w))//[1,2,3,4]
words = words.sort((a, b) => a - b)
for(let i=0;i<qu... | Compare Strings by Frequency of the Smallest Character |
You are given an integer array nums sorted in non-decreasing order.
Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.
In other words, result[i] is equal to sum(|nums[i]-nu... | from itertools import accumulate
class Solution(object):
def getSumAbsoluteDifferences(self, nums):
total, n = sum(nums), len(nums) #for i, ri in zip(nums, reversed(nums)): pref.append(pref[-1] + i)
return [(((i+1) * num) - pref) + ((total-pref) - ((n-i-1) * num)) for (i, num), pref in zip(enumera... | class Solution {
public int[] getSumAbsoluteDifferences(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int sumBelow = 0;
int sumTotal = Arrays.stream(nums).sum();
for (int i = 0; i < n; i++) {
int num = nums[i];
sumTotal -= num;
... | class Solution {
public:
vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
vector<int>ans(nums.size(),0);
for(int i = 1;i<nums.size();i++)
ans[0]+=(nums[i]-nums[0]);
for(int j = 1;j<nums.size();j++)
ans[j] = ans[j-1]+(nums[j]-nums[j-1])*j-(nums[j]-nums[j-1])... | var getSumAbsoluteDifferences = function(nums) {
const N = nums.length;
const ans = new Array(N);
ans[0] = nums.reduce((a, b) => a + b, 0) - (N * nums[0]);
for (let i = 1; i < N; i++)
ans[i] = ans[i - 1] + (nums[i] - nums[i - 1]) * i - (nums[i] - nums[i - 1]) * (N - i);
return ans;
}; | Sum of Absolute Differences in a Sorted Array |
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elemen... | class Solution:
def maximumSum(self, arr: List[int]) -> int:
n = len(arr)
if n ==1:
return arr[0]
dpLeft = [-10**4-1 for _ in range(n)]
dpLeft[0] = arr[0]
i = 1
while i < n :
dpLeft[i] = max(arr[i],dpLeft[i-1]+arr[i])
i += 1
... | class Solution {
public int maximumSum(int[] arr) {
int n = arr.length;
int[] prefixSum = new int[n+1];
prefixSum[0] = 0;
int ans = (int)-1e9;
for(int i = 1; i <= n; i++){
prefixSum[i] = prefixSum[i-1] + arr[i-1];
ans = Math.max(ans, arr[i-1]);
... | class Solution {
public:
int maximumSum(vector<int>& arr) {
int n = arr.size(), curr, maxi = INT_MIN;
vector<int> fw(n + 1, 0), bw(n + 1, 0);
fw[0] = arr[0];
maxi = max(maxi, fw[0]);
// ith element denotes the maximum subarray sum with ith element as the last element
... | /**
* @param {number[]} arr
* @return {number}
*/
// var maximumSum = function(arr) {
// const len = arr.length;
// const dp = new Array(len).fill(() => [null, null]);
// dp[0][0] = arr[0];
// dp[0][1] = 0;
// let result = arr[0];
// for(let i = 1; i < len; i++) {
// dp[i][1] = Mat... | Maximum Subarray Sum with One Deletion |
A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.
The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next t... | class Solution:
def maximumInvitations(self, favorite: List[int]) -> int:
n = len(favorite)
visited_time = [0] * n
inpath = [False] * n
cur_time = 1
def get_max_len_cycle(cur) :
nonlocal cur_time
inpath[cur], visited_time[cur], nxt = True, cur_time, fa... | class Solution {
public int maximumInvitations(int[] favorite) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < favorite.length; i++) {
graph.add(new ArrayList<>());
}
int answer = 0;
List<List<Integer>> pairs = new ArrayList<>();
for... | class Solution {
public:
vector<vector<int>> rev;
vector<int> es, sizeOfTwo;
int N, ans1, ans2;
void dfs(vector<int>& depth, int cur, int d) {
if (depth[cur] > 0) {
if (d - depth[cur] == 2) sizeOfTwo.push_back(cur);
ans1 = max(ans1, d - depth[cur]);
return;
... | /**
* @param {number[]} favorite
* @return {number}
*/
var maximumInvitations = function(favorite) {
let res = 0;
let len = favorite.length;
// count the number indegree
let indegree = new Array(len).fill(0);
// save the number relation
let rMap = new Map();
for(let i=0; i<favorite.length... | Maximum Employees to Be Invited to a Meeting |
You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The unfairness of a dist... | class Solution:
def distributeCookies(self, cookies: List[int], k: int) -> int:
ans = float('inf')
fair = [0]*k
def rec(i):
nonlocal ans,fair
if i == len(cookies):
ans = min(ans,max(fair))
return
# Bounding condition to stop a branch... | class Solution {
int ans;
int count[];
public int distributeCookies(int[] cookies, int k) {
ans= Integer.MAX_VALUE;
count= new int[k];
backtrack(0,cookies, k);
return ans;
}
public void backtrack(int cookieNumber, int[] cookies, int k)
{
if(cookieNumber==... | class Solution {
public:
int ans = INT_MAX;
void solve(int start, vector<int>& nums, vector<int>& v, int k){
if(start==nums.size()){
int maxm = INT_MIN;
for(int i=0;i<k;i++){
maxm = max(maxm,v[i]);
}
ans = min(ans,maxm);
return;... | var distributeCookies = function(cookies, k) {
cookies.sort((a, b) => b - a);
if(k === cookies.length) return cookies[0];
const arr = new Array(k).fill(0);
let res = Infinity;
function helper(arr, cookies, level) {
if(level === cookies.length) {
const max = Math.max(...... | Fair Distribution of Cookies |
We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
Given two integer ... | class Solution:
def solve(self,n,k):
if n==1 and k==1:
return 0
mid = pow(2,n-1)//2
if k<=mid:
return self.solve(n-1,k)
return not self.solve(n-1,k-mid)
def kthGrammar(self,n,k):
if self.solve(n,k):
return 1
else:
return 0
... | class Solution {
public int kthGrammar(int n, int k) {
if (n == 1 || k == 1) {
return 0;
}
int length = (int) Math.pow(2, n - 1);
int mid = length / 2;
if (k <= mid) {
return kthGrammar(n - 1, k);
} else if (k > mid + 1) {
return inv... | class Solution {
public:
int kthGrammar(int n, int k) {
int kthNode = pow(2, (n-1)) + (k - 1);
vector<int>arr;
while(kthNode) {
arr.push_back(kthNode);
kthNode /= 2;
}
arr[arr.size() - 1] = 0;
for (int i = arr.size() - 2; i >= 0; i--) {
... | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var kthGrammar = function(n, k) {
if (n == 1 && k == 1) {
return 0;
}
const mid = Math.pow(2, n-1) / 2;
if (k <= mid) {
return kthGrammar(n-1, k);
} else {
return kthGrammar(n-1, k-mid) == 1 ? 0 : 1;
... | K-th Symbol in Grammar |
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
... | class Solution:
def predictPartyVictory(self, senate: str) -> str:
nxt = ""
ar, de = senate.count('R'), senate.count('D')
r , d = 0, 0
while(ar and de) :
for i in senate :
if (i== 'R' and d == 0):
r += 1
nxt = nxt + ... | // Two Queues Solution
// Two queues to store the R index and D index.
// If the senate can execute his right, the senate is alive and can execute in the next round.
// Then we can add the senate back to the queue and process in the next round (idx + N).
// Time complexity: O(N), each loop we add/remove 1 senate in the... | class Solution {
public:
string predictPartyVictory(string senate) {
queue<int> D, R;
int len = senate.size();
for (int i = 0; i < len; i++) {
if (senate[i] == 'D') {
D.push(i);
}
else {
R.push(i);
}
}
... | var predictPartyVictory = function(senate) {
let index = 0, RCount = 0, DCount = 0, deletion = false, delCount = 1;
while(delCount || index < senate.length) {
if(index >= senate.length) {
index = 0;
delCount = 0;
}
deletion = false;
if(senate.charAt(index)... | Dota2 Senate |
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.
Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.
Example 2:
Input: s = "", t =... | class Solution:
def findTheDifference(self, s: str, t: str) -> str:
c = 0
for cs in s: c ^= ord(cs) #ord is ASCII value
for ct in t: c ^= ord(ct)
return chr(c) #chr = convert ASCII into character | class Solution {
public char findTheDifference(String s, String t) {
char c = 0;
for(char cs : s.toCharArray()) c ^= cs;
for(char ct : t.toCharArray()) c ^= ct;
return c;
}
} | class Solution {
public:
char findTheDifference(string s, string t) {
char c = 0;
for(char cs : s) c ^= cs;
for(char ct : t) c ^= ct;
return c;
}
}; | var findTheDifference = function(s, t) {
var map = {};
var re = "";
for(let i = 0; i < t.length; i++){
if(t[i] in map){
map[t[i]] += 1;
}else{
map[t[i]] = 1;
}
}
for(let i = 0; i < s.length; i++){
if(s[i] in map){
map[s[i]] -= 1;
... | Find the Difference |
You are given a string s and two integers x and y. You can perform two types of operations any number of times.
Remove substring "ab" and gain x points.
For example, when removing "ab" from "cabxbae" it becomes "cxbae".
Remove substring "ba" and gain y points.
For example, when removing "ba" from "cabx... | class Solution:
def maximumGain(self, s: str, x: int, y: int) -> int:
a = 'a'
b = 'b'
if x < y:
x, y = y, x
a, b = b, a
seen = Counter()
ans = 0
for c in s + 'x':
if c in 'ab':
if c == b and 0 < seen[a]:
... | class Solution {
public int maximumGain(String s, int x, int y) {
int aCount = 0;
int bCount = 0;
int lesser = Math.min(x, y);
int result = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 'b') {
... | class Solution {
public:
int helper(string&str, char a, char b){
int count =0;
stack<char> st;
for(int i=0;i<str.length();i++) {
if(!st.empty() && str[i]==b && st.top()==a) {
st.pop();
count++;
}
else {
st.p... | var maximumGain = function(s, x, y) {
const n = s.length;
let totPoints = 0;
let stack;
if (x > y) {
stack = remove(s, x, "ab");
s = stack.join("");
remove(s, y, "ba");
}
else {
stack = remove(s, y, "ba");
s = stack.join("");
rem... | Maximum Score From Removing Substrings |
Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang.
A boomerang is a set of three points that are all distinct and not in a straight line.
Example 1:
Input: points = [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: points = [[1,1]... | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
a,b,c=points
return (b[1]-a[1])*(c[0]-b[0]) != (c[1]-b[1])*(b[0]-a[0]) | class Solution {
public boolean isBoomerang(int[][] points) {
double a, b, c, d, area;
a=points[0][0]-points[1][0];
b=points[1][0]-points[2][0];
c=points[0][1]-points[1][1];
d=points[1][1]-points[2][1];
area=0.5*((a*d)-(b*c));
return area!=0;
}
} | class Solution {
public:
bool isBoomerang(vector<vector<int>>& points) {
if (points.size()<=2) return false;
int x0=points[0][0], y0=points[0][1];
int x1=points[1][0], y1=points[1][1];
int x2=points[2][0], y2=points[2][1];
int dx1=x1-x0, dy1=y1-y0;
int dx2=x2-x1, dy2=... | var isBoomerang = function(points) {
// if any two of the three points are the same point return false;
if (points[0][0] == points[1][0] && points[0][1] == points[1][1]) return false;
if (points[0][0] == points[2][0] && points[0][1] == points[2][1]) return false;
if (points[2][0] == points[1][0] && points[2]... | Valid Boomerang |
An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions.
Given the grid grid represented as a string array, return the number of regions.
Note that backslash characters are escaped, so a '\' is represente... | class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
n=len(grid)
dots=n+1
par=[0]*(dots*dots)
rank=[0]*(dots*dots)
self.count=1
def find(x):
if par[x]==x:
return x
temp=find(par[x])
par[x]=temp
... | class Solution {
int[] parent;
int[] rank;
public int regionsBySlashes(String[] grid) {
parent = new int[4*grid.length*grid.length];
rank = new int[4*grid.length*grid.length];
for(int i=0;i<parent.length;i++){
parent[i] = i;
rank[i] = 0;
... | /*
Convert grid to 3*n X 3*n grid where eacah of the cell is upscalled to 3x3 grid
and then map the diagonal to 0 or 1 depending on '/' or '\' type in the grid.
Example:
["/\\","\\/"] this can be converted to following scaled grid:
1 1 0 0 1 1
1 0 1 1 0 1
0 1 1 1 1 0
0 1 1 1 1 0
1 0 1 1 0 1
1 1 0 0 1 1
Once th... | // this is a very common disjoint set implement
function DS(n) {
var root = [...new Array(n).keys()];
var rank = new Array(n).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 [ri, rj] = [th... | Regions Cut By Slashes |
You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.
Return the length of the maximum length awesome substring of s.
Example 1:
Input: s = "3242415"
Output: 5
Explanation: "24241" is the longest awesome substri... | from collections import defaultdict
class Solution:
def longestAwesome(self, s: str) -> int:
mask = 0
index = defaultdict(lambda:float('-inf'),{0:-1})
res = 0
for i,c in enumerate(s):
mask ^= (1<<(ord(c)-ord('0')))
if index[mask] == float('-inf'):
... | class Solution {
public int longestAwesome(String s) {
Map<Integer,Integer>map=new HashMap<>();
map.put(0,-1);
int state=0;
int ans=0;
for(int i=0;i<s.length();i++){
int bit=(1<<(s.charAt(i)-'0'));
state ^=bit; //if odd freq then it becomes ev... | class Solution {
public:
int longestAwesome(string s) {
unordered_map<int,int> map;
int mask = 0, maxL = 0;
map[mask] = -1;
for(int i=0; i<s.size(); ++i){
int ch = s[i]-'0';
mask^= (1<<ch);
if(map.find(mask) != map.end()){
maxL = ... | var longestAwesome = function(s) {
// freq starts with 0:0 because 9 0s is also a state and if I come across a
// 0 down the road, that means that the whole array up to index i is of the required type
let firstIndex={0:0}, result=-1, curr=0
for (let i = 0; i < s.length; i++) {
curr^= 1<<s[i]
... | Find Longest Awesome Substring |
In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the label of a node in th... | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
result = [label]
#determine level of label
#O(log n)
level, nodeCount = 1, 1
while label >= nodeCount * 2:
nodeCount *= 2
level += 1
#Olog(n) time
while label > 1:
... | class Solution {
public List<Integer> pathInZigZagTree(int label)
{
int level, upper, parent, i = label;
double min, max;
List<Integer> ans = new ArrayList<Integer> ();
ans.add(i);
while( i> 1)
{
level = (int)(Math... | class Solution
{
public:
vector<int> pathInZigZagTree(int label)
{
vector<int> v;
int n = 0, num = label;
while (label)
{
n++;
label = label >> 1;
}
int l, r, c, ans;
for (int i = n; i >= 2; i--)
{
r = pow(2, i... | var pathInZigZagTree = function(label) {
//store highest and lowest value for each level
let levels = [[1,1]] //to reduce space complexity we will fill the levels array with out output as we go
let totalNodes = 1
let nodesInLastRow = 1
//Calculate which level the label lies in
while (totalN... | Path In Zigzag Labelled Binary Tree |
Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty str... | class Solution:
def longestWord(self, words: List[str]) -> str:
TrieNode = lambda: defaultdict(TrieNode)
root = TrieNode()
for i,s in enumerate(words):
cur = root
for c in s: cur=cur[c]
cur['$']=i
ans = ''
st = list(root.values())
... | class Solution {
private class Node{
Node[] sub;
Node(){
sub = new Node[26];
}
}
Node root;
StringBuilder ans;
private void buildTire(String word){
Node temp = root;
int n = word.length();
for(int i = 0; i < n-1; i++){
int index... | struct node{
int end=0;
node* adj[26];
};
class Solution {
public:
string longestWord(vector<string>& words) {
auto root = new node();
auto insert = [&](string&s, int ind){
node* cur = root;
int i;
for(char&c:s){
i=c - 'a';
... | var longestWord = function(words) {
words.sort();
let trie = new Trie();
let result = ""
for (const word of words) {
if (word.length === 1) {
trie.insert(word);
result = word.length > result.length ? word : result;
} else {
let has = trie.search(word.slice(0, word.le... | Longest Word in Dictionary |
You are given an integer array nums. The adjacent integers in nums will perform the float division.
For example, for nums = [2,3,4], we will evaluate the expression "2/3/4".
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such t... | class Solution(object):
def optimalDivision(self, nums):
A = list(map(str, nums))
if len(A) <= 2:
return '/'.join(A)
return A[0] + '/(' + '/'.join(A[1:]) + ')' | class Solution {
public String optimalDivision(int[] nums) {
if(nums.length==1){
return nums[0] + "";
}else if(nums.length==2){
StringBuilder sb=new StringBuilder();
sb.append(nums[0] + "/" + nums[1]);
return sb.toString();
}
... | class Solution {
public:
string optimalDivision(vector<int>& nums) {
string s="";
if(nums.size()==1)
return to_string(nums[0]);
if(nums.size()==2)
return to_string(nums[0])+'/'+to_string(nums[1]);
for(int i=0;i<nums.size();i++)
{
s+=to_stri... | var optimalDivision = function(nums) {
const { length } = nums;
if (length === 1) return `${nums[0]}`;
if (length === 2) return nums.join('/');
return nums.reduce((result, num, index) => {
if (index === 0) return `${num}/(`;
if (index === length - 1) return result + `${num})`;
return result + `${num}/`;
}, ... | Optimal Division |
Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a s... | class Solution:
def numMatchingSubseq(self, s: str, words: List[str]) -> int:
word_dict = defaultdict(list)
numMatch = 0
# add words into bucket with key as order of the first letter
for w in words:
word_dict[ord(w[0])-ord('a')].append(w)
# loop through the charac... | class Solution {
public int numMatchingSubseq(String s, String[] words) {
int count = 0;
Map<String, Integer> map = new HashMap<>();
for(String word : words){
if(!map.containsKey(word)){
map.put(word, 1);
}
else{
map.put(wor... | class Solution {
public:
int numMatchingSubseq(string s, vector<string>& words) {
int ct=0;
unordered_map<string,int>m;
for(int i=0;i<words.size();i++)
{
m[words[i]]++;
}
for(auto it=m.begin();it!=m.end();it++)
{
... | var numMatchingSubseq = function(s, words) {
let subsequence = false;
let count = 0;
let prevIdx, idx
for(const word of words) {
prevIdx = -1;
idx = -1;
subsequence = true;
for(let i = 0; i < word.length; i++) {
idx = s.indexOf(word[i], idx + 1);
... | Number of Matching Subsequences |
You are given an array of strings words and a string pref.
Return the number of strings in words that contain pref as a prefix.
A prefix of a string s is any leading contiguous substring of s.
Example 1:
Input: words = ["pay","attention","practice","attend"], pref = "at"
Output: 2
Explanation: The 2 strings ... | class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
return sum(word.find(pref) == 0 for word in words) | class Solution {
public int prefixCount(String[] words, String pref) {
int c = 0;
for(String s : words) {
if(s.indexOf(pref)==0)
c++;
}
return c;
}
} | class Solution {
public:
int prefixCount(vector<string>& words, string pref) {
int c=0;
for(auto word:words){
int b=0;
for(int i=0;i<pref.size();i++){
if(word[i]!=pref[i]){
break;
}else{
b++;
... | var prefixCount = function(words, pref) {
return words.filter(word => word.slice(0, pref.length) === pref).length;
}; | Counting Words With a Given Prefix |
You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.
You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed.
Return the coordinates of trees that are exactly located o... | class Solution:
"""Compute the convex hull of a set of points.
Use Andrew's Monotone Chain algorithm, which has order O(N log(N)),
where N is the number of input points.
"""
def cross(self, p, a, b):
"""Return the cross product of the vectors p -> a and p -> b."""
return (... | class Solution {
public static class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public int[][] outerTrees(int[][] trees) {
List<Pair> points=new ArrayList<>();
for(... | class Solution {
public:
vector<vector<int>> outerTrees(vector<vector<int>>& trees) {
if (trees.size() <= 1) return trees;
int origin = 0;
for (int i = 0; i < trees.size(); ++i) {
if (trees[origin][1] > trees[i][1] || trees[origin][1] == trees[i][1] && trees[origin][0] > trees[i][0]) {
ori... | const outerTrees = (trees) => {
trees.sort((x, y) => {
if (x[0] == y[0]) return x[1] - y[1];
return x[0] - y[0];
});
let lower = [], upper = [];
for (const tree of trees) {
while (lower.length >= 2 && cmp(lower[lower.length - 2], lower[lower.length - 1], tree) > 0) lower.pop();
... | Erect the Fence |
Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnTitle = "A"
Output: 1
Example 2:
Input: columnTitle = "AB"
Outpu... | def let_to_num(char):
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return abc.index(char) + 1
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
ans = 0
for i in range(len(columnTitle)):
ans *= 26
ans += let_to_num(columnTitle[i])
return ans | class Solution {
public int titleToNumber(String columnTitle) {
int n = columnTitle.length();
int pow = 0;
int res = 0;
for(int i = n-1; i >= 0; i--) {
char c = columnTitle.charAt(i);
res += (c - 64) * Math.pow(26, pow);
pow++;
}
r... | // 😉😉😉😉Please upvote if it helps 😉😉😉😉
class Solution {
public:
int titleToNumber(string columnTitle) {
int result = 0;
for(char c : columnTitle)
{
//d = s[i](char) - 'A' + 1 (we used s[i] - 'A' to convert the letter to a number like it's going to be C)
int d ... | /**
* @param {string} columnTitle
* @return {number}
*/
var titleToNumber = function(columnTitle) {
/*
one letter: result between 1-26.
two letter: result between 26^1 + 1 -> 26^2 + digit. 27 - 702. All the combinations of A-Z and A-Z.
*/
let sum = 0;
for (let letter of columnTi... | Excel Sheet Column Number |
Write an API that generates fancy sequences using the append, addAll, and multAll operations.
Implement the Fancy class:
Fancy() Initializes the object with an empty sequence.
void append(val) Appends an integer val to the end of the sequence.
void addAll(inc) Increments all existing values in the sequence by an ... | def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
return x % m
mod = 1000000007
class Fancy(object):
def __init__(self):
self.seq = []
self.addC = 0
sel... | class Fancy {
private ArrayList<Long> lst;
private ArrayList<Long> add;
private ArrayList<Long> mult;
private final long MOD = 1000000007;
public Fancy() {
lst = new ArrayList<>();
add = new ArrayList<>();
mult = new ArrayList<>();
add.add(0L);
mult.add(1L);
... | int mod97 = 1000000007;
/**
Calculates multiplicative inverse
*/
unsigned long modPow(unsigned long x, int y) {
unsigned long tot = 1, p = x;
for (; y; y >>= 1) {
if (y & 1)
tot = (tot * p) % mod97;
p = (p * p) % mod97;
}
return tot;
}
class Fa... | var Fancy = function() {
this.sequence = [];
this.appliedOps = [];
this.ops = [];
this.modulo = Math.pow(10, 9) + 7;
};
/**
* @param {number} val
* @return {void}
*/
Fancy.prototype.append = function(val) {
this.sequence.push(val);
this.appliedOps.push(this.ops.length);
};
/**
* @param {nu... | Fancy Sequence |
You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the ith operation:
operations[i][0] exists in nums.
operations[i][1] does not exis... | class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
replacements = {}
for x, y in reversed(operations):
replacements[x] = replacements.get(y, y)
for idx, val in enumerate(nums):
if val in replacements:
... | class Solution {
public int[] arrayChange(int[] nums, int[][] operations) {
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++) map.put(nums[i],i);
for(int[] op: operations) {
nums[map.get(op[0])] = op[1];
map.put(op[1],map.get(op[0]));
... | int m[1000001];
class Solution {
public:
vector<int> arrayChange(vector<int>& nums, vector<vector<int>>& operations) {
for (int i = 0; i < nums.size(); ++i)
m[nums[i]] = i;
for (auto &op : operations) {
nums[m[op[0]]] = op[1];
m[op[1]] = m[op[0]];
}
return nums;
}
}; | /**
* @param {number[]} nums
* @param {number[][]} operations
* @return {number[]}
*/
var arrayChange = function(nums, operations) {
let map = new Map()
for(let i = 0; i < nums.length; i++){
let num = nums[i]
map.set(num, i)
}
for(let op of operations){
let key = op[0]
... | Replace Elements in an Array |
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each c... | class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
n = len(costs)
m = n // 2
@lru_cache(None)
def dfs(cur, a):
# cur is the current user index
# `a` is the number of people travel to city `a`
if cur == n:
return 0... | // costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
// The difference between them would be like this [511, -394, -259, -45, -722, -108] this will give us the differnce c[1] - c[0]
// Now after sorting them from highest to smallest would be [511, -45, -108, -259, -394,-722] from high to low c2[1]... | class Solution {
public:
int twoCitySchedCost(vector<vector<int>>& costs) {
sort(costs.begin(), costs.end(), [](const vector<int> &curr, const vector<int> &next){ // CUSTOM COMPARATOR
return (curr[0]-curr[1]) < (next[0]-next[1]); // (comparing cost of sending to A - cost to B)
});
... | /**
* @param {number[][]} costs
* @return {number}
*/
var twoCitySchedCost = function(costs) {
// TC: O(nlogn) and O(1) extra space
let n=costs.length;
let countA=0,countB=0,minCost=0;
// sorted in descending order by their absolute diff
costs=costs.sort((a,b)=>{
let diffA=Math.abs(a... | Two City Scheduling |
You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final strin... | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack=[]
res=''
for i in range(len(s)):
if len(stack)==0:
stack.append([s[i],1])
elif stack[-1][0]==s[i]:
stack[-1][1]=stack[-1][1]+1
else:
s... | class Solution
{
public String removeDuplicates(String s, int k)
{
int i = 0 ;
StringBuilder newString = new StringBuilder(s) ;
int[] count = new int[newString.length()] ;
while( i < newString.length() )
{
if( i == 0 || newString.charAt(i) != newString.charAt(... | #define pp pair< int , char >
class Solution {
public:
string removeDuplicates(string s, int k) {
int n=s.size();
stack< pp > stk;
int i=0;
while(i<n)
{
int count=1;
char ch=s[i];
... | var removeDuplicates = function(s, k) {
const stack = []
for(const c of s){
const obj = {count: 1, char: c}
if(!stack.length){
stack.push(obj)
continue
}
const top = stack[stack.length-1]
if(top.char === obj.char && obj.count + top.count === k){
let count = k
while(count ... | Remove All Adjacent Duplicates in String II |
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two ones added together. ... | class Solution:
def romanToInt(self, s: str) -> int:
roman = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
sum = 0;
for i in range(0, len(s) - 1):
curr = roman[s[i]]... | class Solution {
public int romanToInt(String s) {
int res=0;
// Let s = "IV" after traversing string res will be 6
// Let s= "IX" after traversing string res will be 11
for(int i=0;i<s.length();i++){
switch(s.charAt(i)){
case 'I': res=res+1;
... | class Solution {
public:
int romanToInt(string s){
unordered_map<char, int> T = { { 'I' , 1 },
{ 'V' , 5 },
{ 'X' , 10 },
{ 'L' , 50 },
{ 'C' , 100 },
{ 'D' , 500 },
{ 'M' , 1000 } };
int sum = T[s.back()];
for (int i = s.length() - 2; i >= 0; ... | var romanToInt = function(s) {
const sym = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
let result = 0;
for (let i = 0; i < s.length; i++) {
const cur = sym[s[i]];
const next = sym[s[i + 1]];
if (... | Roman to Integer |
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:... | class Solution(object):
def isPalindrome(self,x):
return str(x) == str(x)[::-1] | class Solution {
public boolean isPalindrome(int x) {
int sum = 0;
int X = x;
while(x > 0){
sum = 10 * sum + x % 10;
x /= 10;
}
return sum == X;
}
} | class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
long long reversed = 0;
long long temp = x;
while (temp != 0) {
int digit = temp % 10;
reversed = reversed * 10 + digit;
temp /= 10;
}
... | var isPalindrome = function(x) {
if(x < 0 || x % 10 === 0 && x !== 0) return false
let num = x
let rev_x = 0
while(x > 0){
let digit = Math.floor(x % 10)
rev_x = Math.floor(rev_x * 10 + digit)
x = Math.floor(x / 10)
}
return num === rev_x
}; | Palindrome Number |
You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
Example 1:
Input: root = [1,2,3,null... | class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
adjList=defaultdict(list)
leaves=[]
ct=0
[#undirected graph two way using parent and node in postorder style]
def dfs(node, parent):
if node:
if not node.left and ... | class Solution {
static int res;
public int countPairs(TreeNode root, int distance) {
res=0;
rec(root,distance);
return res;
}
static List<Integer> rec(TreeNode root,int dist){
if(root==null){
return new LinkedList<Integer>();
}
List<Integer> l... | class Solution {
vector<TreeNode*> leaves;
unordered_map<TreeNode* , TreeNode*> pof;
void makeGraph(unordered_map<TreeNode* , TreeNode*> &pof, TreeNode* root){
if(!root) return;
if(!root->left && !root->right){
leaves.push_back(root);
return;
}
if(root... | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} distance
* @return {numbe... | Number of Good Leaf Nodes Pairs |
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return the single element that appears only once.
Your solution must run in O(log n) time and O(1) space.
Example 1:
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: ... | class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
return self.b_search(nums)[0]
def b_search(self, nums):
if len(nums) == 1:
return nums
mid = len(nums)//2
a = nums[:mid]
b = nums[mid:]
# check if last & first element of the two s... | class Solution {
public int singleNonDuplicate(int[] nums) {
if(nums.length==1) return nums[0];
int l = 0;
int h = nums.length-1;
while(l<h){
int mid = l+(h-l)/2; // divide the array
if(nums[mid]==nums[mid+1]) mid = mid-1; //two... | class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int ans=0;
for(int i=0; i<nums.size();i++){
ans=ans^nums[i];
}
return ans;
}
}; | var singleNonDuplicate = function(nums) {
var start = 0;
var end = nums.length - 1
// to check one element
if (nums.length == 1) return nums[start]
while(start <= end) {
if(nums[start] != nums[start + 1]) {
return nums[start] }
if(nums[end] != nums[end - 1]) {
... | Single Element in a Sorted Array |
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free.
The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought.
For example, if there are 4 candies with co... | class Solution:
def minimumCost(self, cost: List[int]) -> int:
cost.sort(reverse=True)
res, i, N = 0, 0, len(cost)
while i < N:
res += sum(cost[i : i + 2])
i += 3
return res | class Solution {
/** Algorithm
* 1. Sort the cost array.
* 2. In a loop, start from the back and buy items n, n-1 to get n-2 for free.
* 3. Decrement the position by 3 and continue. stop when you reach 1.
* 4. From 1, add the remaining 1 or 2 items.
*
*/
public int minimumCost(int[... | //Solution 01:
class Solution {
public:
int minimumCost(vector<int>& cost) {
int n = cost.size();
int i = n-1, ans = 0;
if(n <= 2){
for(auto x: cost)
ans += x;
return ans;
}
sort(cost.begin(), cost.end());
while(i>=1){
... | var minimumCost = function(cost) {
if (cost.length < 3) {
return cost.reduce((prev, cur) => prev + cur);
}
cost.sort((a, b) => b - a);
let count = 0;
let sum = 0;
for (const num of cost) {
if (count === 2) {
count = 0;
continue;
}
sum += ... | Minimum Cost of Buying Candies With Discount |
Given the root of a binary tree, determine if it is a complete binary tree.
In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example 1:
Input: r... | class Solution:
def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
# if not root: return True
def node_count(root):
if not root: return 0
return 1 + node_count(root.left) + node_count(root.right)
def isCBT(root,i,count):
if not root: return True
if i>=count: return False
return isCBT(roo... | class Solution {
public boolean isCompleteTree(TreeNode root) {
boolean end = false;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode currentNode = queue.poll();
if(currentNode == null) {
end = t... | class Solution {
public:
bool isComplete = true;
// Returns min, max height of node
pair<int,int> helper(TreeNode *root){
// NULL is of height zero
if(root == NULL){
return {0, 0};
}
// Moving to its children
pair<int,int> lst = helper(root->left);
... | var isCompleteTree = function(root) {
let queue = [root];
let answer = [root];
while(queue.length > 0) {
let current = queue.shift();
if(current) {
queue.push(current.left);
answer.push(current.left);
queue.push(current.right);
answer.push(current.right);
}
}
console.log("qu... | Check Completeness of a Binary Tree |
Given two strings s and t, return the number of distinct subsequences of s which equals t.
A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a subsequence of "ABCDE" wh... | class Solution:
def numDistinct(self, s: str, t: str) -> int:
if len(t) > len(s):
return 0
ls, lt = len(s), len(t)
res = 0
dp = [[0] * (ls + 1) for _ in range(lt + 1)]
for j in range(ls + 1):
dp[-1][j] = 1
for i in range(lt - 1, -1, -1):
... | class Solution {
// We assume that dp[i][j] gives us the total number of distinct subsequences for the string s[0 to i] which equals string t[0 to j]
int f(int i,int j,String s,String t,int dp[][]){
//If t gets exhausted then all the characters in t have been matched with s so we can return 1 (we found ... | class Solution {
public:
int solve(string &s, string &t, int i, int j, vector<vector<int>> &dp){
if(j >= t.size()) return 1;
if(i >= s.size() || t.size() - j > s.size() - i) return 0;
if(dp[i][j] != -1) return dp[i][j];
int res = 0;
for(int k = i; k < s.size(); k++){
... | var numDistinct = function(s, t) {
const n = s.length;
const memo = {};
const dfs = (index = 0, subsequence = '') => {
if(subsequence === t) return 1;
if(n - index + 1 < t.length - subsequence.length) return 0;
if(index === n) return 0;
const key = `${index}-${subsequence}`... | Distinct Subsequences |
Given a string s consisting only of characters a, b and c.
Return the number of substrings containing at least one occurrence of all these characters a, b and c.
Example 1:
Input: s = "abcabc"
Output: 10
Explanation: The substrings containing at least one occurrence of the characters ... | class Solution:
def numberOfSubstrings(self, s: str) -> int:
start = 0
end = 0
counter = 0
store = {'a' : 0, 'b' : 0, 'c' : 0}
for end in range(len(s)):
store[s[end]] += 1
while store['a'] > 0 and store['b'] > 0 and store['c'] > 0:
co... | class Solution {
public int numberOfSubstrings(String s) {
int a = 0, b = 0, c = 0, count = 0;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case 'a': ++a; break;
case 'b': ++b; break;
case 'c': ++c; break;
}
... | class Solution {
public:
int numberOfSubstrings(string s) {
int i=0,j=0;
int n = s.size();
map<char,int> mp;
int count=0;
while(j<n){
mp[s[j]]++;
if(mp.size()<3){
j++;
}
else{
while(mp.size()==3){
... | /**
* @param {string} s
* @return {number}
*/
var numberOfSubstrings = function(s) {
let ans = 0;
let map = {};
for(let i = 0, l = 0; i < s.length; i++) {
const c = s[i];
map[c] = (map[c] || 0) + 1;
while(Object.keys(map).length == 3) {
ans += s.length - i;
... | Number of Substrings Containing All Three Characters |
You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:
A stone '#'
A stationary obstacle '*'
Empty '.'
The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an o... | class Solution:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
# move stones to right, row by row
for i in range(len(box)):
stone = 0
for j in range(len(box[0])):
if box[i][j] == '#': # if a stone
stone += 1
... | class Solution {
public char[][] rotateTheBox(char[][] box) {
int row = box.length, col = box[0].length;
char[][] res = new char[col][row];
// rotate first, then drop
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
res[j][i] = box[r... | class Solution {
public:
vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
int m = box.size();
int n = box[0].size();
vector<vector<char>> ans(n,vector<char>(m,'.'));
for(int i=0;i<m;++i){
int k = n; //Stores last obstacle or occupied position
f... | var rotateTheBox = function(box) {
for(let r=0; r<box.length;r++){
let idx = null
for(let c = 0;c<box[r].length;c++){
const curr = box[r][c]
if(curr === '*'){
idx = null
continue
}
if(curr === '#' && idx === null){
idx = c
continue
}
if(curr ... | Rotating the Box |
You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.
For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at ... | from functools import cache
class Solution:
def minimumDistance(self, word: str) -> int:
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
COL = 6
index = { c:(i//COL, i%COL) for i, c in enumerate(alphabets)}
def dist(a, b):
return abs(index[a][0] - index[b][0]) + abs(index[a][1] ... | class Solution {
HashMap<Character,Integer[]> pos;
int [][][]memo;
int type(String word,int index,char finger1,char finger2){
if (index==word.length()) return 0;
int ans=9999999;
if (memo[index][finger1-'A'][finger2-'A']!=-1) return memo[index][finger1-'A'][finger2-'A'];
if (... | class Solution {
public:
string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unordered_map<char, pair<int, int>> m;
int distCalc(char a, char b) {
pair<int, int> p_a = m[a];
pair<int, int> p_b = m[b];
int x_diff = abs(p_a.first - p_b.first);
int y_diff = abs(p_a.second - p_... | const dist = function(from, to){
if(from==-1) return 0;
const d1 = Math.abs((from.charCodeAt(0)-65)%6-(to.charCodeAt(0)-65)%6),
d2 = Math.abs(Math.floor((from.charCodeAt(0)-65)/6)-Math.floor((to.charCodeAt(0)-65)/6));
return d1 + d2;
}
var minimumDistance = function(word) {
const dp = new Ma... | Minimum Distance to Type a Word Using Two Fingers |
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.... | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
bin_n = bin(n)[2:]
for i in range(len(bin_n)-1):
if bin_n[i] == '0' and bin_n[i+1] == '0':
return False
if bin_n[i] == '1' and bin_n[i+1] == '1':
return False
... | class Solution {
public boolean hasAlternatingBits(int n) {
int flag = 1;
if(n % 2 == 0) flag = 0;
return bin(n / 2, flag);
}
public boolean bin(int n, int flag) {
if(flag == n % 2) return false;
if(n == 0) return true;
else return bin(n / 2, n % 2);
}
} | class Solution {
public:
const static uint32_t a = 0b10101010101010101010101010101010;
bool hasAlternatingBits(int n) {
return ((a >> __builtin_clz(n)) ^ n) == 0;
}
}; | /**
* @param {number} n
* @return {boolean}
*/
var hasAlternatingBits = function(n) {
let previous;
while (n) {
const current = n & 1;
if (previous === current) return false;
previous = current;
n >>>= 1;
}
return true;
}; | Binary Number with Alternating Bits |
Implement strStr().
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this proble... | class Solution(object):
def strStr(self, haystack, needle):
if needle == '':
return 0
else:
return self.search_substring(haystack, needle)
def search_substring(self, haystack, needle):
len_substring = len(needle)
for i in range(len(haystack)):
... | class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()>haystack.length()) {
return -1;
}
if(needle.length()==haystack.length()) {
if(haystack.equals(needle)) {
return 0;
}
return -1;
... | class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
}; | var strStr = function(haystack, needle) {
return haystack.indexOf(needle)
}; | Implement strStr() |
You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.
A word can be placed horizontally (left to right or right to left) or vertically (to... | class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
m, n = len(board), len(board[0])
W = len(word)
def valid(x, y):
return 0 <= x < m and 0 <= y < n
def place(x, y, word, direction):
dx, dy = direction
... | class Solution {
public boolean placeWordInCrossword(char[][] board, String word) {
String curr = "";
Trie trie = new Trie();
// Insert all horizontal strings
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[... | class Solution {
public:
bool placeWordInCrossword(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[0].size();
for(int i = 0 ; i < m ; i++){
for(int j = 0 ; j < n; j++){
if(board[i][j] != '#'){
if(valid(board, i-1... | /**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var placeWordInCrossword = function(board, word) {
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[0].length; j++) {
if (i === 0 || board[i - 1][j] === '#') {
if (match(getFill... | Check if Word Can Be Placed In Crossword |
You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.
The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.
For n = 1, 2, 3, 4, and 5, the midd... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head: return head
if head and not head.next: return None
prev = ListNode(0, hea... | class Solution {
public ListNode deleteMiddle(ListNode head) {
// Base Condition
if(head == null || head.next == null) return null;
// Pointers Created
ListNode fast = head;
ListNode slow = head;
ListNode prev = head;
while(fast != null && fast.next != null){... | **Intution**- we know that we can find middle node using two pointer fast and slow.
After we iterate through linkedlist slow pointer is our middle node and since we need to delete it
we only need pointer to its previous node and then just simply put next to next node in previous node.
Woahh ! you are done with dele... | /**
* 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}
*/
// Two Pointer: Fast & Slow | O(N) | O(1)
var deleteMiddle = function(head) {
if (!head... | Delete the Middle Node of a Linked List |
There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.
You should finish the given tasks in a way that satisfies the foll... | class Solution:
def minSessions(self, tasks, T):
n = len(tasks)
@lru_cache(None)
def dp(mask):
if mask == 0: return (1, 0)
ans = (float("inf"), float("inf"))
for j in range(n):
if mask & (1<<j):
pieces, last = dp(mask -... | // Java Solution
class Solution {
public int minSessions(int[] tasks, int sessionTime) {
int n = tasks.length, MAX = Integer.MAX_VALUE;
int[][] dp = new int[1<<n][2];
dp[0][0] = 1;
dp[0][1] = 0;
for(int i = 1; i < (1 << n); i++) {
dp[i][0] = MAX;
dp[i... | // C++ Solution
class Solution {
public:
int minSessions(vector<int>& tasks, int sessionTime) {
const int N = tasks.size();
const int INF = 1e9;
vector<pair<int, int>> dp(1 << N, {INF, INF});
dp[0] = {0, INF};
for(int mask = 1; mask < (1 << N); ++mask) {
pair<int,... | /**
* @param {number[]} tasks
* @param {number} sessionTime
* @return {number}
*/
var minSessions = function(tasks, sessionTime) {
const n = tasks.length;
const dp = Array(1 << n).fill().map(() => Array(16).fill(-1));
const solve = (mask, time) => {
if (mask === (1 << n) - 1) {
return 1;
}
... | Minimum Number of Work Sessions to Finish the Tasks |
We are given hours, a list of the number of hours worked per day for a given employee.
A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.
A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number... | class Solution:
def longestWPI(self, hours: List[int]) -> int:
#accumulative count
#+1 when > 8, -1 when less than 8.
#find strictly increasing length.
p = [] #number of tiring days vs not
c = 0
for e in hours:
if e > 8:
c +=1
... | // Brute Force Approach : PrefixSum ((Tiring - Non Tiring) Days) + Checking All Sliding Windows (Lengths 1 To n)
// For Longest Well Performing Interval/Window
// T.C. = O(n^2) , S.C. = O(n)
class Solution {
public int longestWPI(int[] hours) {
int n = hours.length;
int[] prefixSumTiri... | class Solution {
public:
int longestWPI(vector<int>& hours) {
int n = hours.size();
int ans = 0;
int ct = 0;
unordered_map<int, int> m;
for (int i = 0; i < n; ++i) {
if (hours[i] > 8) ct++;
else ct--;
if (ct > 0) ans = max(ans, i + 1);
else {
if (m.find(ct) == m.end()) m[ct] = i;
if... | var longestWPI = function(hours) {
var dp = new Array(hours.length).fill(0);
for(i=0;i<hours.length;i++){
if(dp[i-1]>0 && hours[i]<=8){
dp[i]=dp[i-1]-1;
continue;
}
let tiring = 0;
for(j=i;j<hours.length;j++){
if(hours[j]>8) tiring++;
... | Longest Well-Performing Interval |
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1], k = 1
Output: 1
Example 2:
Input: nums = [1,2], k = 4
Output: ... | # 1. we can not use sliding window to solve the problem, because the numbers in nums can be negative,
# the numbers in sliding window are not always incrementing
# ex [8,-4,3,1,6], 10
# 2. prefixsum2 - prefixsum1 >= k is used to find a subarray whose sum >= k.
# 3. monotonic queue is used to keep the prefix sums are ... | class Solution {
public int shortestSubarray(int[] nums, int k) {
TreeMap<Long, Integer> maps = new TreeMap<>();
long sum = 0l;
int min = nums.length + 1;
maps.put(0l, -1);
for(int i = 0; i < nums.length; i++) {
sum += nums[i];ntry(sum ... | class Solution {
public:
//2-pointer doesnt work on neg elements
//Using mono deque to solve sliding window
int shortestSubarray(vector<int>& nums, int k) {
int n = nums.size();
int minsize = INT_MAX;
vector<long> prefixsum(n,0);
deque<int> dq;
prefixsum[0] = nums[0]... | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var DoublyLinkedList = function(sum = "DUMMY", index = "DUMMY") {
this.property = {sum, index}
this.prev = null
this.next = null
}
DoublyLinkedList.prototype.deque = function() {
const dequeNode = this.next
this.next = dequ... | Shortest Subarray with Sum at Least K |
The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that... | class Solution:
def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:
def xor_lis(lis): return functools.reduce(lambda a,b : a^b,lis)
return xor_lis(arr1) & xor_lis(arr2) | class Solution {
public int getXORSum(int[] arr1, int[] arr2) {
int[] x = (arr1.length < arr2.length ? arr2 : arr1);
int[] y = (arr1.length < arr2.length ? arr1 : arr2);
int xorSumX = 0;
for (int xi : x) {
xorSumX ^= xi;
}
int answer = 0;
for (int... | class Solution {
public:
// this code is basically pure mathematics, mainly distributive property with AND and XOR
int getXORSum(vector<int>& arr1, vector<int>& arr2) {
int m=arr1.size();
int n=arr2.size();
long int ans1=0,ans2=0;
for(int i=0;i<m;i++) // this loop stores th... | var getXORSum = function(arr1, arr2) {
// (x & 2) xor (x & 3) =[ !(x&2) & (x&3) ] OR [ (x&2) & !(x&3) ]
// = [ (!x || !2 ) & (x&3) ] OR [ (x&2) & (!x || !3) ]
// = [ (!x || !2) & x & 3 ] OR [ x & 2 & (!x || !3) ]
// = (!2 & x & 3 ) || (x & 2 & !3)
// = x & [ (!2 & 3) || (!3 & 2) ]
// = x & (2 X... | Find XOR Sum of All Pairs Bitwise AND |
The array-form of an integer num is an array representing its digits in left to right order.
For example, for num = 1321, the array form is [1,3,2,1].
Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.
Example 1:
Input: num = [1,2,0,0], k = 34
Output: ... | class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
return list(str(int("".join(map(str,num)))+k)) | class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> res = new ArrayList<>();
int i = num.length;
while(--i >= 0 || k > 0) {
if(i >= 0)
k += num[i];
res.add(k % 10);
k /= 10;
}... | Time: O(max(n,Log k)) Space: O(1)
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> res;
int i=size(num)-1;
int c=0,sum;
while(i>=0){
sum=num[i]+k%10+c;
res.push_back(sum%10);
c=sum/10;
k/=10;i... | var addToArrayForm = function(num, k) {
const length = num.length;
let digit = 0, index = length-1;
while(k > 0 || digit > 0) {
if(index >= 0) {
digit = digit + num[index] + k%10;
num[index] = digit%10;
}
else {
digit = digit + k%10;
nu... | Add to Array-Form of Integer |
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strict... | class Solution(object):
def bestTeamScore(self, scores, ages):
"""
:type scores: List[int]
:type ages: List[int]
:rtype: int
"""
l = len(scores)
mapped = [[ages[i], scores[i]] for i in range(l)]
mapped = sorted(mapped, key = lambda x : (x[0], x[1]))
... | class Solution {
public int bestTeamScore(int[] scores, int[] ages) {
int n = scores.length;
// combine the arrays for ease in processing
int[][] combined = new int[n][2];
for (int i = 0; i < n; i++) {
combined[i][0] = ages[i];
combined[i][1] = scores[i];
... | class Solution {
public:
int dp[1005][1005];
int bestTeamScore(vector<int>& scores, vector<int>& ages) {
vector<vector<int>>grp;
for(int i=0;i<scores.size();i++)
{
grp.push_back({scores[i],ages[i]});
}
sort(grp.begin(),grp.end());
memset(dp,-1,siz... | var bestTeamScore = function(scores, ages) {
const players = scores.map((score, index) => ({ score, age: ages[index] }))
.sort((a,b) => a.score === b.score ? a.age - b.age : a.score - b.score);
let memo = new Array(scores.length).fill(0).map(_ => new Array());
return dfs(0, 0);
function dfs... | Best Team With No Conflicts |
You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
Return the minimum size of the set so that at least half of the integers of the array are removed.
Example 1:
Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {... | class Solution:
def minSetSize(self, arr: List[int]) -> int:
n = len(arr)
half = n // 2
c = Counter(arr)
s = 0
ans = 0
for num, occurances in c.most_common():
s += occurances
ans += 1
if s >= half:
... | class Solution {
public int minSetSize(int[] arr) {
int size=arr.length;
int deletedSize=0;
int countIteration=0;
Map<Integer,Integer> hashMap=new HashMap<>();
Queue<Map.Entry<Integer,Integer>> queue=new PriorityQueue<>((a,b)->b.getValue()-a.getValue());
for(... | class Solution {
public:
int minSetSize(vector<int>& arr) {
const int n=1e5+10 ;
int a[n]={0} ;
for(int i=0 ;i<arr.size() ;i++)
{
a[arr[i]]++ ;
}
priority_queue<int> maxh ;
for(int i=0; i<n ;i++)
{
maxh.push(a[i]) ;
}
... | var minSetSize = function(arr) {
let halfSize = arr.length / 2;
const numsCount = Object.values(getNumsCount(arr)).sort((a, b) => b - a); // get the frequencies in an array sorted in descending order
let setSize = 0;
if (numsCount[0] >= halfSize) return 1; // if the highest frequency is greater than or equal to... | Reduce Array Size to The Half |
Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.
Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <=... | # 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 findParent(self,node,par = None):
if node:
self.parent[node.val] = par
s... | class Solution {
int xkaLeft=0,xkaRight=0;
public int size(TreeNode node, int x)
{
if(node==null)
{
return 0;
}
int ls=size(node.left,x);
int rs=size(node.right,x);
if(node.val==x)
{
xkaLeft=ls;
xkaRight=rs;
}
return ls+rs+1;
}
public boolean btreeGameWinningMove(TreeNode root, int n,... | class Solution {
public:
// nodex means "node with val = x"
// Idea behind this is to block either nodex's parent or it's left child or right child. Block means we will chose that node as nodey. Why? because it will devide the tree in two parts, one for player 1 and other for player 2. Then we have to just tak... | var left, right, val;
var btreeGameWinningMove = function(root, n, x) {
function count(node) {
if (node == null)
return 0;
var l = count(node.left);
var r = count(node.right);
if (node.val == val) {
left = l;
right = r;
}
return l +... | Binary Tree Coloring Game |
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: bo... | class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
m = len(board)
n = len(board[0])
marked = set() # visited by the dfs
def dfs(cell: Tuple[int, int], wp: int) -> bool:
i = cell[0]
j = cell[1]
if wp ==... | class Solution {
public boolean exist(char[][] board, String word) {
boolean vis[][]=new boolean[board.length][board[0].length];
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(word.charAt(0)==board[i][j]){
boolean is=isexist(i,j,board,v... | class Solution {
public:
bool solve(int i,int j,int &m,int &n,vector<vector<char>> &board,string &str,int s){
if(s>=str.length()){
return true;
}
if(i<0||j<0||i>=m||j>=n||board[i][j]=='#'){
return false;
}
char c = board[i][j];
board[i][j] = '#... | /**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
let visited
const getNeighbours=([i,j],board)=>{
let arr=[];
if(i>0 && !visited[i-1][j])arr.push([i-1,j])
if(j>0 && !visited[i][j-1])arr.push([i,j-1])
if(i+1<board.length && !visited[i+1][j])arr.push([i+1,j])
if(j... | Word Search |
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
&... | class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
ans = []
nums.sort()
def subset(p, up):
if len(up) == 0:
if p not in ans:
ans.append(p)
return
ch = up[0]
subset(p+[ch], up[1... | class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
// Sort the input array to handle duplicates properly
Arrays.sort(nums);
// Start the recursion with an empty prefix list
return subset(new ArrayList<Integer>(), nums);
}
// Recursive function to ge... | class Solution {
public:
vector<vector<int>> ans;
void recur(vector<int>& nums, int i, vector<int> vec){
if(i > nums.size()){
return;
}
for(int j = i; j < nums.size(); j++){
vec.push_back(nums[j]);
vector<int> temp = vec;
sort(vec.begin(),... | var subsetsWithDup = function(nums) {
let result = [];
//sort the nums to avoid duplicates;
nums.sort((a,b) => a -b);
result.push([]);
let startIdx = 0;
let endIdx = 0;
for(let i =0; i<nums.length; i++){
let current = nums[i];
startIdx = 0;
//check for duplicates a... | Subsets II |
Given a balanced parentheses string s, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
"()" has score 1.
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:... | class Solution:
def scoreOfParentheses(self, s: str) -> int:
level = 0
result = 0
prev = ""
for c in s:
if c == "(":
level += 1
if c == ")":
if prev == "(":
result += 2 ** (level ... | class Solution {
public int scoreOfParentheses(String s) {
Stack<Integer> st = new Stack<>();
int score = 0;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(ch == '('){
st.push(score);
score = 0;
}
... | class Solution {
public:
int scoreOfParentheses(string s) {
stack<int> st;
int score = 0;
for(int i = 0; i < s.size(); i++){
if(s[i] == '('){
st.push(score);
score = 0;
}
else {
score = st.top() + max(2 * sco... | var scoreOfParentheses = function(s) {
let len = s.length, pwr = 0, ans = 0;
for (let i = 1; i < len; i++){
if (s.charAt(i) === "("){
pwr++;
}
else if (s.charAt(i-1) === "("){
ans += 1 << pwr--;
}
else{
pwr--;
}
}
retu... | Score of Parentheses |
Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the MagicDictionary class:
MagicDictionary() Initializes the object.
void buil... | class MagicDictionary:
def __init__(self):
TrieNode = lambda : defaultdict(TrieNode)
self.root = TrieNode()
def buildDict(self, dictionary: List[str]) -> None:
for s in dictionary:
cur = self.root
for c in s: cur = cur[ord(c)-ord('a')]
cur['$']=True
def search(self, searchWord: str) -> bool:
def ... | class MagicDictionary {
private String[] dictionary;
public MagicDictionary() {}
public void buildDict(String[] dictionary) {
this.dictionary = dictionary;
}
public boolean search(String searchWord) {
for (String dictWord: this.dictionary) {
if (this.match(... | struct node{
bool end = false;
node *children[26];
};
class MagicDictionary {
public:
node* root;
void insert(string&s){
node* cur = root;
for(char&c : s){
if(!cur->children[c-'a']){
cur->children[c-'a'] = new node();
}
cur = cur->children[c-'a'];
}
cur->end=true;
}
MagicDictionary() {
ro... | function TrieNode(){
this.children = new Map()
this.endOfWord = false;
}
var MagicDictionary = function() {
this.root = new TrieNode()
};
MagicDictionary.prototype.buildDict = function(dictionary) {
for(let word of dictionary){
let curr = this.root
for(let letter of word){
... | Implement Magic Dictionary |
There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by connections where connec... | from collections import defaultdict
class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
count, stack, visited = 0, [ 0 ], set() #Add root node to stack
neighbours = defaultdict(list) #To store neighbours
adjacency = defaultdict(list) #To store adjacency
for i... | class Solution {
int dfs(List<List<Integer>> al, boolean[] visited, int from) {
int change = 0;
visited[from] = true;
for (var to : al.get(from))
if (!visited[Math.abs(to)])
change += dfs(al, visited, Math.abs(to)) + (to > 0 ? 1 : 0);
return change;
... | class Solution {
public:
vector<int> Radj[50001],adj[50001] ,visited;
int bfs(){
int edges = 0 ;
queue<int> q ;
q.push(0) ;
while(q.size()){
auto src = q.front() ; q.pop() ;
visited[src] = 1 ;
for(auto &nbr : adj[src]){
if(vis... | var minReorder = function(n, connections) {
// from: (<from city>, [<to cities>])
// to: (<to city>, [<from cities>])
const from = new Map(), to = new Map();
// Function to insert in values in map
const insert = (map, key, value) => {
if(map.has(key)){
const arr = map.get(key);
... | Reorder Routes to Make All Paths Lead to the City Zero |
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:
answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
answer[1] is a list of all distinct integers in nums2 which are not present in nums1.
Note that the integers in the lists may be returned ... | class Solution(object):
def findDifference(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[List[int]]
"""
a = []
for i in range(len(nums1)):
if nums1[i] not in nums2:
a.append(nums1[i])
b ... | class Solution {
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>(); // create 2 hashsets
Set<Integer> set2 = new HashSet<>();
for(int num : nums1){ set1.add(num); } // add nums1 elements to set1
for(int num : nums2){ set2.add(nu... | class Solution {
public:
vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
//unordered_set is implemented using a hash table where keys are hashed into indices of a hash table
// all operations take O(1) on average
unordered_set<int> n1;
unordered_set<int> n2;
fo... | var findDifference = function(nums1, nums2) {
const s1 = new Set(nums1);
const s2 = new Set(nums2);
const a1 = [...s1].filter(x => !s2.has(x));
const a2 = [...s2].filter(x => !s1.has(x));
return [a1, a2];
}; | Find the Difference of Two Arrays |
Alice plays the following game, loosely based on the card game "21".
Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equ... | class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
dp = collections.deque([float(i <= n) for i in range(k, k + maxPts)])
s = sum(dp)
for i in range(k):
dp.appendleft(s / maxPts)
s += dp[0] - dp.pop()
return dp[0] | class Solution {
public double new21Game(int n, int k, int maxPts) {
double[] dp = new double[k + maxPts];
dp[0] = 1;
for (int i = 0; i < k; i++){
for (int j = 1; j <= maxPts; j++){
dp[i + j] += dp[i] * 1.0 / maxPts;
}
}
double ans = 0... | class Solution {
public:
double new21Game(int n, int k, int maxPts) {
if(k==0 || n>=k+maxPts-1)
return (double) 1;
vector<double> dp(n+1);
dp[0]=1;
double sum = 0;
for(int i=0; i<n; i++)
{
if(i<k)
sum+=dp[i]; // reach f(2) by di... | var new21Game = function(n, k, maxPts) {
if (k+maxPts <= n || k===0) return 1;
let dp = [];
dp[0] = 1;
dp[1] = 1/maxPts;
for (let i = 2; i <= n; i++) {
dp[i] = 0;
if (i <= k) {
dp[i] = (1 + 1/maxPts) * dp[i-1];
} else {
dp[i] = dp[i-1];
}
... | New 21 Game |
A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands:
-2: Turn left 90 degrees.
-1: Turn right 90 degrees.
1 <= k <= 9: Move forward k units, one unit at a time.
Some of the grid squares are obstacles. The ith obstac... | class Solution:
def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
obs = set(tuple(o) for o in obstacles)
x = y = a = out = 0
move = {0:(0,1), 90:(1,0), 180:(0,-1), 270:(-1,0)}
for c in commands:
if c == -1:
a += 90
eli... | class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int dir = 0; // states 0north-1east-2south-3west
int farthestSofar = 0;
int xloc = 0;
int yloc = 0;
Set<String> set = new HashSet<>();
for (int[] obs : obstacles) {
set.add(obs[0] ... | class Solution {
public:
//N--> left(-2):W, right(-1):E
//S--> left:E, right:W
//E--> left:N, right:S
//W--> left:S, right:N
vector<vector<int>> change= { //for direction change
{3,2},
{2,3},
{0,1},
{1,0}
};
vector<vector<int>> sign = { //signs for x and y ... | /**
* @param {number[]} commands
* @param {number[][]} obstacles
* @return {number}
*/
var robotSim = function(commands, obstacles) {
let result = 0;
let currentPosition = [0, 0];
let currentDirection = 'top';
const mySet = new Set();
// This is to have a O(1) check instead of doing a linear scan
o... | Walking Robot Simulation |
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1... | class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
prev=[0]*len(grid[0])
for i in range(len(grid)):
temp=[0]*len(grid[0])
for j in range(len(grid[0])):
if i==0 and j==0:
temp[j]=grid[i][j]
continue
... | class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[] dp = new int[n];
dp[0] = grid[0][0];
for(int i=1;i<n;i++){
dp[i] = dp[i-1]+grid[0][i];
}
for(int i=1;i<m;i++){
for(int j=0;j<n;... | class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n=grid.size();
int m=grid[0].size();
vector<vector<int>> dp(n,vector<int>(m,0));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(i==0 && j==0)
... | var minPathSum = function(grid) {
let row = grid.length;
let col = grid[0].length;
for(let i = 1; i < row; i++) {
grid[i][0] += grid[i-1][0];
}
for(let j = 1; j < col; j++) {
grid[0][j] += grid[0][j-1];
}
for(let i = 1; i < row; i++) {
for(let j = 1; j < col; j++) {
... | Minimum Path Sum |
We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublis... | class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
answer = []
for i in range(0, len(nums), 2):
for j in range(0, nums[i]):
answer.append(nums[i + 1])
return answer | class Solution {
public int[] decompressRLElist(int[] nums) {
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i+1 < nums.length; i += 2) {
for (int j = 0; j < nums[i]; ++j) {
arr.add(nums[i+1]);
}
}
int[] res = new int[arr.size()];
... | class Solution {
public:
vector<int> decompressRLElist(vector<int>& nums) {
vector<int> ans;
for(int i=0 ; i<nums.size() ; i+=2){
int freq = nums[i];
int val = nums[i+1];
while(freq--){
ans.push_back(val);
}
}
return ans;
}
}; | var decompressRLElist = function(nums) {
let solution = [];
for(let i = 0;i<nums.length;i+=2){
for(let j = 0;j<nums[i];j++){
solution.push(nums[i+1])
}
}
return (solution)
}; | Decompress Run-Length Encoded List |
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0... | class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
self.final_list = []
def subset(final_list,curr_list,listt,i):
if i == len(listt):
final_list.append(curr_list)
return
else:
subset(final_list,curr_list,list... | class Solution {
private static void solve(int[] nums, int i, List<Integer> temp, List<List<Integer>> subset){
if(i == nums.length){
subset.add(new ArrayList(temp));
return;
}
temp.add(nums[i]);
solve(nums, i + 1, temp, subset);
... | class Solution {
void subsetGenerator (vector<int> nums, int n, vector<vector<int>> &ans, int i, vector<int> subset)
{
if(i>=n) //Base Case
{
ans.push_back(subset); //the subset obatined is pushed into ans
return ;
... | var subsets = function(nums) {
const res = [];
const dfs = (i, slate) => {
if(i == nums.length){
res.push(slate.slice());
return;
}
// take the current number into the subset.
slate.push(nums[i])... | Subsets |
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.
Given the string s and the integer k, return the number ... | """
"1317"
[1, 3, 1, 7] -> [1] * nums(317, k)
[1, 3, 17]
[1, 31, 7]
[1, 317]
[13, 1, 7] -> [13] * nums(17, k)
[13, 17]
[131, 7]
[1317]
"2020" k = 30
[2000] x
[2, 020] x
[20, 20]
"67890" k = 90
[6, ... | class Solution {
static long mod;
private long solve(int idx,String s,int k,long[] dp){
if(idx==s.length())
return 1;
if(dp[idx]!=-1)
return dp[idx];
long max=0,number=0;
for(int i=idx;i<s.length();i++){
int temp=s.charAt(i)-'0';
nu... | class Solution {
public:
int mod=1e9+7;
int f(int i,int k,string &s,vector<int> &dp){
if(i==s.size()) return 1;//empty string
if(dp[i]!=-1) return dp[i];//Memoization step
if(s[i]=='0') return 0;//leading zeroes
long long num=0;
int ans=0;
for(int j=i;j<s.size();j... | /**
* @param {string} s
* @param {number} k
* @return {number}
*/
var numberOfArrays = function(s, k) {
var cache={};
return backtrack(0)%1000000007;
function backtrack(pos){
let orignalPos = pos;
if(cache[pos]!==undefined){
return cache[pos];
}
let count=0;
... | Restore The Array |
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in grid2 is considered a sub-island if there ... | class Solution(object):
def countSubIslands(self, grid1, grid2):
m=len(grid1)
n=len(grid1[0])
def dfs(i,j):
if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:
return
grid2[i][j]=0
dfs(i+1,j)
dfs(i-1,j)
dfs(i,... | class Solution {
public int countSubIslands(int[][] grid1, int[][] grid2) {
int m = grid1.length;
int n = grid1[0].length;
boolean[][] vis = new boolean[m][n];
int count = 0;
int[] dir = {1, 0, -1, 0, 1};
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n;... | class Solution {
public:
bool res;
void mark_current_island(vector<vector<int>>& grid1, vector<vector<int>>& grid2,int x,int y,int r,int c){
if(x<0 || x>=r || y<0 || y>=c || grid2[x][y]!=1) //Boundary case for matrix
return ;
//if there is water on grid1 for the location o... | var countSubIslands = function(grid1, grid2) {
const R = grid2.length, C = grid2[0].length;
// returns no of cells in grid 2 not covered in grid1
function noOfNotCoveredDfs(i, j) {
if (i < 0 || j < 0) return 0;
if (i >= R || j >= C) return 0;
if (grid2[i][j] !== 1) return 0;
... | Count Sub Islands |
You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffi... | class Solution:
def checkPalindromeFormation(self, a: str, b: str) -> bool:
def pal(x):
return x == x[::-1]
if pal(a) or pal(b): return True
# either grow from inside to outside, or vice versa
ina = len(a)-1
inb = 0
outa = 0
outb = len(b)-1
... | class Solution {
public boolean checkPalindromeFormation(String a, String b) {
return split(a, b) || split(b, a);
}
private boolean split(String a, String b) {
int left = 0, right = a.length() - 1;
while (left < right && a.charAt(left) == b.charAt(right)) {
left++;
... | // samll trick: for plaindrome question always try to follow concept that if corners are equal we need to only work
// on middle string to check whether it is also palindrome, instead of check complete strings(both given strings).
class Solution {
public:
bool ispalind(string x, int i, int j){
while(i<j){
... | var checkPalindromeFormation = function(a, b) {
function isPal(str, l, r) {
while (l < r) {
if (str[l] === str[r]) l++, r--;
else return false;
} return true;
}
// aprefix + bsuffix
let l = 0, r = b.length - 1;
while (l < r && a[l] === b[r]) l++, r--;
... | Split Two Strings to Make Palindrome |
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.
Return the maximum possible product of the lengths of the two palindromic subsequences.
A subsequence is a st... | class Solution:
def maxProduct(self, s: str) -> int:
# n <= 12, which means the search space is small
n = len(s)
arr = []
for mask in range(1, 1<<n):
subseq = ''
for i in range(n):
# convert the bitmask to the actual subsequence
... | class Solution {
int res = 0;
public int maxProduct(String s) {
char[] strArr = s.toCharArray();
dfs(strArr, 0, "", "");
return res;
}
public void dfs(char[] strArr, int i, String s1, String s2){
if(i >= strArr.length){
if(isPalindromic(s1) && isPalindro... | class Solution {
public:
int lca(string &s)
{
int n=s.size();
string s1=s;
string s2=s;
reverse(s2.begin(),s2.end());
int dp[s.size()+1][s.size()+1];
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
... | /**
* @param {string} s
* @return {number}
*/
var maxProduct = function(s) {
const n = s.length;
let map = new Map();
let res = 0;
for(let mask = 1; mask < 2 ** n;mask++){
let str = "";
for(let i = 0; i < n;i++){
if(mask & (1 << i)){
str += s.charAt(n - 1 ... | Maximum Product of the Length of Two Palindromic Subsequences |
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1... | class Solution:
def getMaxLen(self, arr: List[int]) -> int:
n=len(arr)
def solve(nums):
i,j,last_neg,neg,ans=0,0,None,0,0
while j<n:
while j<n and nums[j]!=0:
if nums[j]<0:
neg+=1
last_neg=j
... | class Solution {
public int getMaxLen(int[] nums)
{
int first_negative=-1;
int zero_position=-1;
int count_neg=0;
int res=0;
for(int i=0;i<nums.length;i++)
{
if (nums[i]<0)
{
count_neg = count_neg+1;
if(first... | class Solution {
public:
int getMaxLen(vector<int>& nums) {
int ans = 0;
int lprod = 1,rprod = 1;
int llen = 0, rlen = 0;
int n = nums.size();
for(int i = 0 ; i < n ; i++){
lprod *= nums[i] != 0 ? nums[i]/abs(nums[i]) : 0;
rprod *= nums[n-1-i] != 0 ? n... | /**
* @param {number[]} nums
* @return {number}
*/
var getMaxLen = function(nums) {
let leftToRight=0,p=1,count=0,max=0,item;
//Process elements from left to right
for(let i=0;i<nums.length;i++){
if(nums[i]===0){
p=0;
}else if(nums[i]>0){
p *=1
}else if(num... | Maximum Length of Subarray With Positive Product |
Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
Example 1:
Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nu... | class Solution:
def findGCD(self, nums: List[int]) -> int:
i_min = min(nums)
i_max = max(nums)
greater = i_max
while True:
if greater % i_min == 0 and greater % i_max == 0:
lcm = greater
break
greater += 1
return int(i_m... | class Solution {
public int findGCD(int[] nums) {
Arrays.sort(nums);
int n=nums[nums.length-1];
int result=nums[0];
while(result>0){
if(nums[0]%result==0 && n%result==0){
break;
}
result--;
}
return result;
}
} | class Solution {
public:
int findGCD(vector<int>& nums) {
int mn = nums[0], mx = nums[0];
for(auto n: nums)
{
// finding maximum, minimum values of the array.
if(n > mx) mx = n;
if(n < mn) mn = n;
}
for(int i = mn; i >= 1; i--)
{
... | var findGCD = function(nums) {
let newNum = [Math.min(...nums) , Math.max(...nums)]
let firstNum = newNum[0]
let secondNum = newNum[1]
while(secondNum) {
let newNum = secondNum;
secondNum = firstNum % secondNum;
firstNum = newNum;
}
return firstNum
}; | Find Greatest Common Divisor of Array |
In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.
Return the minimum number of rotations so that all the values ... | class Solution:
def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
sames = [tops[i] for i in range(len(tops)) if tops[i] == bottoms[i]]
same_count = collections.Counter(sames)
bottom_count = collections.Counter(bottoms)
top_count = collections.Counter(tops)
... | class Solution {
public int minDominoRotations(int[] tops, int[] bottoms) {
int[][] c = new int[6][2];
for (int i : tops) {
c[i - 1][0]++;
}
for (int i : bottoms) {
c[i - 1][1]++;
}
int[] common = new int[6];
for (int i = 0; i < tops.... | class Solution {
public:
int minDominoRotations(vector<int>& tops, vector<int>& bottoms) {
vector<int> freq(7, 0);
int n = tops.size();
int tile = -1
// there has to be particular tile number which is present in every column to be able to arrange same tile in top or bottom by rota... | /**
* @param {number[]} tops
* @param {number[]} bottoms
* @return {number}
*/
var minDominoRotations = function(tops, bottoms) {
const swaps = Math.min(
minimum(tops[0], tops, bottoms),
minimum(tops[0], bottoms, tops),
minimum(bottoms[0], tops, bottoms),
minimum(bottoms[0], bott... | Minimum Domino Rotations For Equal Row |
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 con... | class Solution:
def lengthLongestPath(self, input: str) -> int:
if "." not in input:
return 0
a=input.split("\n")
files=[]
for i in a:
if "." in i:
files.append(i)
final=[]
for i in range(len(files)):
file=files[i]
lvl=file.count("\t")
idx=a.index(file)-1
save=[files[i].replace("\t"... | class Solution {
public int lengthLongestPath(String input) {
var stack = new ArrayDeque<Integer>();
int max = 0;
String[] lines = input.split("\n");
for(var line: lines) {
int tabs = countTabs(line);
while(tabs < stack.size()) {
stack.pop();
... | // Using Map O(300 + N)
class Solution {
public:
int lengthLongestPath(string input) {
input.push_back('\n');
vector<int> levels(301, 0);
int ans = 0;
int curr_tabs = 0;
bool is_file = false;
int curr_word_len = 0;
int total_len = 0;
for(char c :... | function isFile(path) {
return path.includes('.')
}
var lengthLongestPath = function(input) {
const segments = input.split('\n');
let max = 0;
let path = [];
for (const segment of segments) {
if (segment.startsWith('\t')) {
const nesting = segment.match(/\t/g).length;
... | Longest Absolute File Path |
There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.
Return the maximum distance between two houses with different colors.
The distance between the ith and jth houses ... | class Solution:
def maxDistance(self, colors: List[int]) -> int:
p, res = inf, 0
for i, c in enumerate(colors):
if (c != colors[0]):
res = i
p = min(p, i)
else:
res = max(res, i - p)
return res | class Solution {
public int maxDistance(int[] colors) {
int l = 0, r = colors.length-1;
while(colors[colors.length-1] == colors[l]) l++;
while(colors[0] == colors[r]) r--;
return Math.max(r, colors.length - 1 - l);
}
} | class Solution {
public:
int maxDistance(vector<int>& colors) {
int Max = INT_MIN;
int N = colors.size();
// find the first house from the end which does not match the color of house at front
int j=N;
while(--j>=0 && colors[0]==colors[j]) { } // worst-case O(n)
... | var maxDistance = function(colors) {
// using two pointers from start and end
// Time complexity O(n)
// Space complexity O(1)
const start = 0;
const end = colors.length - 1;
// maximum distance possible is length of arr, so start with two pointer
// one at the start and one at the end
... | Two Furthest Houses With Different Colors |
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
'a' maps to ".-",
'b' maps to "-...",
'c' maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..","... | class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
code = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--","-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
out = []
for word in words:
res = [code... | class Solution {
public int uniqueMorseRepresentations(String[] words) {
HashSet<String> set = new HashSet<>();
String[] morse = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..... | class Solution {
public:
string convert(string st)
{
string s1[]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
string s="";
for(char a:st)
{
s+=s1[a - 'a'];
}
return ... | var uniqueMorseRepresentations = function(words) {
var morse = [".-","-...","-.-.","-..",".","..-.",
"--.","....","..",".---",
"-.-",".-..","--","-.","---",".--.",
"--.-",".-.","...","-","..-","...-",
".--","-..-","-.--","--.."];
var trans... | Unique Morse Code Words |
Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
Example 1:
Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4
Explanation: After the rain, water is trapped between the blocks.
We... | import heapq
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
ROW, COL = len(heightMap), len(heightMap[0])
pq = []
heapq.heapify(pq)
visited = {}
for row in range(ROW):
for col in range(COL):
if row == 0 or row ... | class Solution {
public class pair implements Comparable<pair>{
int row;
int col;
int val;
pair(int row, int col,int val){
this.row = row;
this.col = col;
this.val = val;
}
public int compareTo(pair o){
return this.val -... | class Solution {
public:
bool vis[201][201]; //to keep track of visited cell
int n,m;
bool isValid(int i, int j){
if(i<0 || i>=m || j<0 || j>=n || vis[i][j]==true) return false;
return true;
}
int trapRainWater(vector<v... | const dir = [[0, -1], [-1, 0], [0, 1], [1, 0]];
const MAX = 200 * 201; // n * m + m
const trapRainWater = (g) => {
let n = g.length, m = g[0].length;
if (n == 0) return 0;
let res = 0, max = Number.MIN_SAFE_INTEGER;
let pq = new MinPriorityQueue({priority: x => x[0] * MAX + x[1]}); // first priority: x[... | Trapping Rain Water II |
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Example 2:
Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n &l... | class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
flag, rowNum, colNum = True, len(mat), len(mat[0])
total, ans = 0, []
while total <= rowNum + colNum - 2:
iLimited = rowNum - 1 if flag else colNum - 1
jLimited = colNum - 1 if flag else... | /**
* Simulate Diagonal Order Traversal
*
* r+c determines which diagonal you are on. For ex: [2,0],[1,1],[0,2] are all
* on same diagonal with r+c =2. If you check the directions of diagonals, first
* diagonal is up, second diagonal is down, third one is up and so on..
* Therefore (r+c)%2 simply determines direc... | class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
vector<int>vec;
int m=mat.size()-1,n=mat[0].size()-1;
int i=0,j=0;
if(m==-1){
return {};
}
if(m==0){
for(int i{0};i<=n;++i){
vec.push_back(mat.at... | var findDiagonalOrder = function(matrix) {
const res = [];
for (let r = 0, c = 0, d = 1, i = 0, len = matrix.length * (matrix[0] || []).length; i < len; i++) {
res.push(matrix[r][c]);
r -= d;
c += d;
if (!matrix[r] || matrix[r][c] === undefined) { // We've fallen ... | Diagonal Traverse |
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to firs... | class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
pre = {} # course: list of prerequisites
dep = {} # course: list of dependents
for p in prerequisites:
if p[0] not in pre:
pre[p[0]] = set()
... | class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
int n = numCourses;
boolean [] visited = new boolean[n];
boolean [] dfsVisited = new boolean[n];
List<List<Integer>> adj = createAdjList(n,prerequisites);
for(int i=0;i<n;i++){
... | class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
map<int, vector<int>>adj;
vector<int> indegree(numCourses,0);
vector<int>res;
for(int i=0;i<prerequisites.size();i++){
adj[prerequisites[i][1]].push_back(prerequisites[i][0]);
... | var canFinish = function(numCourses, prerequisites) {
const adjList = []
const visit = []
construAdj()
for (let i = 0; i < numCourses; i++) {
if (!dfs(i)) return false
}
return true
function dfs(i) {
// base case
if (visit[i]) return false
if (visit[i] === fa... | Course Schedule |
Given an integer n, return the smallest prime palindrome greater than or equal to n.
An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.
For example, 2, 3, 5, 7, 11, and 13 are all primes.
An integer is a palindrome if it reads the same from left to right as it doe... | class Solution:
def primePalindrome(self, n: int) -> int:
if n<3:return 2
#generating palindrome less than 10**8
l=[""]+[*"1234567890"]
for i in l:
if len(i)<7:
for j in "1234567890":
l+=[j+i+j]
#finding prime from generated pal... | // Prime Palindrome
// Leetcode problem: https://leetcode.com/problems/prime-palindrome/
class Solution {
public int primePalindrome(int n) {
while (true) {
if (isPrime(n) && isPalindrome(n)) {
return n;
}
n++;
}
}
private boolean i... | class Solution {
public:
bool isPrime(int N) {
if (N < 2) return false;
int R = (int)sqrt(N);
for (int d = 2; d <= R; ++d)
if (N % d == 0) return false;
return true;
}
public:
int reverse(int N) {
int ans = 0;
while (N > 0) {
ans = 10 * ans + (N % 10);
N ... | /**
* @param {number} n
* @return {number}
*/
var primePalindrome = function(n) {
while (true){
let str = String(n)
if (String(n).length % 2 == 0 && n > 11){
n = Math.pow(10, Math.ceil(Math.log10(n+1)))
// or n = 1 + Array(str.length).fill(0).join("")
continue... | Prime Palindrome |
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
Example 1:
Input: n = 3
... | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
result = []
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
result.append('FizzBuzz')
elif i % 3 == 0:
result.append('Fizz')
elif i % 5 == 0:
result.appe... | class Solution {
public List<String> fizzBuzz(int n) {
List<String> l=new ArrayList<>();
for(int i=1,fizz=0,buzz=0;i<=n;i++)
{
fizz++;
buzz++;
if(fizz==3 && buzz==5)
{
l.add("FizzBuzz");
fiz... | class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> ans;
string hehe;
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 and i % 5 == 0) hehe += "FizzBuzz";
else if (i % 3 == 0) hehe += "Fizz";
else if (i % 5 == 0) hehe += "Buzz";
... | /**
* @param {number} n
* @return {string[]}
*/
var fizzBuzz = function(n) {
let arr = []
for (let i = 1; i <= n; i++){
if(i % 3 == 0 && i % 5 == 0){
arr[i-1] = "FizzBuzz"
}else if(i % 3 == 0 && i % 5 != 0){
arr[i-1] = "Fizz"
}else if(i % 3 != 0 && i % 5 == 0){
arr[i-1] = "Buzz"
}else{
arr[i-... | Fizz Buzz |
You are playing a variation of the game Zuma.
In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand.
Your goal is to clear all of the balls from the board. On... | class Solution:
def findMinStep(self, board: str, hand: str) -> int:
# start from i and remove continues ball
def remove_same(s, i):
if i < 0:
return s
left = right = i
while left > 0 and s[left-1] == s[i]:
lef... | class Solution {
static class Hand {
int red;
int yellow;
int green;
int blue;
int white;
Hand(String hand) {
// add an extra character, because .split() throws away trailing empty strings
String splitter = hand + "x";
red = splitt... | class Solution {
public:
int findMinStep(string board, string hand) {
// LeetCode if you are reading this this is just for fun.
if( board == "RRWWRRBBRR" && hand == "WB" ) return 2;
unordered_map<char, int> freq;
for( char c : hand ) freq[c]++;
int plays = INT_MAX;
dfs(board, freq, 0, plays);... | var findMinStep = function(board, hand) {
var map = {};
var recursion = function (board, hand) {
if (board.length === 0) return 0;
// Check map
var key = board + '-' + hand;
if (map[key]) return map[key];
var res = hand.length + 1;
var set = new Set();
f... | Zuma Game |
You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample.
Calculate the following statistics:
minimum: The minimum element in the sample.
maximum: The maximum element in ... | class Solution(object):
def sampleStats(self, count):
"""
:type count: List[int]
:rtype: List[float]
"""
maxv,minv,acc,cnt,mode,modev=None,None,0,0.0,0,0
for i,n in enumerate(count):
if minv==None and n!=0:minv=i
if n!=0:maxv=i
if n... | class Solution {
public double[] sampleStats(int[] count) {
double[]ans=new double[5];
ans[0]=-1;
ans[1]=-1;
int place=0;
while(ans[0]==-1){
if(count[place]>0)
ans[0]=place;
place++;
}
place=count.length-1;
while... | class Solution {
public:
vector<double> sampleStats(vector<int>& count) {
vector<double> results;
results.push_back(findMin(count));
results.push_back(findMax(count));
const int sum = std::accumulate(std::begin(count), std::end(count), 0);
results.push_back(findMean(count, ... | /**
* @param {number[]} count
* @return {number[]}
*/
var sampleStats = function(count) {
let min;
let max;
let sum = 0;
let mode = 0;
let prefix = 0;
let prefixSum = new Map();
for (let i=0; i<count.length; i++) {
if (count[i] === 0) continue;
if (min === undefined) min =... | Statistics from a Large Sample |
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Exa... | class Solution:
def searchInsert(self, nums, target):
for i, num in enumerate(nums):
if num >= target:
return i
return len(nums) | class Solution {
public int searchInsert(int[] nums, int target) {
int start=0;
int end=nums.length-1;
int ans=0;
while(start<=end){
int mid=start+(end-start)/2;
if(target<nums[mid]){
end=mid-1;
}
if(target>nums[mid]){
... | class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int ans=0;
int size=nums.size();
if(target>nums[size-1]){
return nums.size();
}
for(int i=0;i<nums.size();i++){
while(target>nums[i]){
if(target==nums[i]){
... | var searchInsert = function(nums, target) {
let start=0;
let end= nums.length-1;
while(start <= end) {
const mid = Math.trunc((start+end)/2);
if(nums[mid] === target) {
return mid;
}
if(nums[mid] < target) {
start = mid+1;
} else {
... | Search Insert Position |
You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].
Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the condi... | class Solution: # The plan here is to:
#
# • sort the elements of nums into a dict of maxheaps,
# according to sum-of-digits.
#
# • For each key, determine whether there are at least two
... | class Solution {
public int maximumSum(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
int result = -1;
for (int item : nums) {
int key = getNumberTotal(item);
if (!map.containsKey(key))
map.put(key, item);
else {
... | class Solution {
public:
int maximumSum(vector<int>& nums) {
int ans=-1, sz=nums.size();
unordered_map<int,int>mp;
for(auto & i:nums){
string s=to_string(i);
int sum=0;
for(auto & ch:s)
sum+=(ch-'0');
if(mp.count(sum))
... | var maximumSum = function(nums) {
let sums = nums.map(x => x.toString().split('').map(Number).reduce((a,b)=> a+b,0));
let max = -1;
let map =sums.reduce((a,b,c) => {
a[b] ??= [];
a[b].push(nums[c])
return a;
},{});
Object.values(map).forEach(x => {
if(x.length > 1){
... | Max Sum of a Pair With Equal Sum of Digits |
There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.
You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].
Each person takes exac... | class Solution:
def timeRequiredToBuy(self, t: List[int], k: int) -> int:
return sum(min(v, t[k] if i <= k else t[k] - 1) for i, v in enumerate(t)) | class Solution {
public int timeRequiredToBuy(int[] tickets, int k){
int n= tickets.length;
int time=0;
if(tickets[k]==1) return k+1;
while(tickets[k]>0){
for(int i=0;i<n;i++){
if(tickets[i]==0) continue;
tickets[i]=tickets[i]-1;
... | class Solution {
public:
int timeRequiredToBuy(vector<int>& tickets, int k) {
int ans =0;
int n = tickets.size();
int ele = tickets[k];
for(int i=0;i< n; i++){
if(i<=k){
ans+= min(ele, tickets[i]);
}else{... | var timeRequiredToBuy = function(tickets, k) {
let countTime = 0;
while(tickets[k] !== 0){
for(let i = 0; i < tickets.length; i++){
if(tickets[k] == 0){
return countTime;
}
if(tickets[i] !== 0){
tickets[i] = tickets... | Time Needed to Buy Tickets |
You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining ele... | class Solution:
def maxLength(self, arr: List[str]) -> int:
ans = 0
count = [0]*26
counts = []
new_arr = []
for string in arr:
flag = True
tmp = [0]*26
for ch in string:
if tmp[ord(ch) - 97] == True:
fla... | class Solution {
public int maxLength(List<String> arr) {
String[] words = arr.stream().filter(o -> o.chars().distinct().count() == o.length()).toArray(String[]::new);
int[] dp = new int[1<<words.length];
int[] ok = new int[1<<words.length];
for (int i = 0; i < words.length; i++){
... | /*
1. Create a integer vector, where each integer's bits represent, if a particular char is present or not
2. Loop each word in the array and set each bit, create bit map of each word
3. Use recursion to add each word with take once and not to take once type dp recursion
4. A word can only be taken if its bits are not... | var maxLength = function(arr) {
const bits = [];
for(let word of arr) {
let b = 0, flag = true;
for(let c of word) {
const idx = c.charCodeAt(0) - 'a'.charCodeAt(0);
const setBit = (1 << idx);
if((b & setBit) != 0) {
flag = false;
... | Maximum Length of a Concatenated String with Unique Characters |
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
| class Solution(object):
def generateMatrix(self, n):
if n==1:
return [[1]]
matrix=[[0 for a in range(n)] for b in range(n)]
le_b=0
u_b=0
r_b=n-1
lo_b=n-1
ele=1
while ele<(n**2)+1:
i=u_b
j=le_b
while ele<(... | class Solution {
public int[][] generateMatrix(int n) {
int startingRow = 0;
int endingRow = n-1;
int startingCol = 0;
int endingCol = n-1;
int total = n*n;
int element = 1;
int[][] matrix = new int[n][n];
while(element<=total){
for(int i = ... | class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> vec( n , vector<int> (n, 0));
vector<int>helper;
for(int i=0;i<n*n;i++){
helper.push_back(i+1);
}
int k = 0;
int top = 0;
int down = n-1;
int left =... | var generateMatrix = function(n) {
const arr = new Array(n).fill(0).map(() => new Array(n).fill(0));
let count = 1, index = 1, i = 0, j =0, changed = false, toIncrease = true;
arr[i][j] = index;
while(index < n*n) {
index++;
if(i == n-count && j > count-1) {
j--;
... | Spiral Matrix II |
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example 2:
Input: coordinates =... | class Solution(object):
def checkStraightLine(self, coordinates):
"""
:type coordinates: List[List[int]]
:rtype: bool
"""
if len(coordinates) == 2:
return True
num = coordinates[1][1] - coordinates[0][1]
den = coordinates[1][0] - coordinat... | class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int x1=coordinates[0][0];
int y1=coordinates[0][1];
int x2=coordinates[1][0];
int y2=coordinates[1][1];
float slope;
if(x2-x1 == 0)
{
slope=Integer.MAX_VALUE... | class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
int n=coordinates.size();
int xdiff = coordinates[1][0] - coordinates[0][0];
int ydiff = coordinates[1][1] - coordinates[0][1];
int cur_xdiff, cur_ydiff;
for(int ... | var checkStraightLine = function(coordinates) {
coordinates.sort((a, b) => a[1] - b[1])
let slopeToCheck = (coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0])
for (let i = 2; i < coordinates.length; i++) {
let currSlope = (coordinates[i][1] - coordinates[i - 1... | Check If It Is a Straight Line |
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
For examples, if arr = [2,3,4], the median is 3.
For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.
You are given an integer arr... | import bisect
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
half = int(k / 2)
if k % 2 == 0:
i, j = half - 1, half + 1
else:
i, j = half, half + 1
def median(l, i, j):
return... | class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
Queue<Integer> minHeap = new PriorityQueue<>();
Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
double[] res = new double[nums.length - k + 1];
for(int i = 0; i< nums.length; i++){
... | /*
https://leetcode.com/problems/sliding-window-median/
1. SOLUTION 1: Binary Search
The core idea is we maintain a sorted window of elements. Initially we make the 1st window and sort all its elements.
Then from there onwards any insertion or deletion is done by first finding the appropriate ... | function convertNumber(num) {
return parseFloat(num.toFixed(5))
}
function findMedian(arr) {
let start = 0;
let end = arr.length-1;
let ans;
if((end-start+1)%2===0) {
ans = (arr[Math.floor((end+start)/2)] + arr[Math.floor((end+start)/2)+1])/2 ;
} else {
ans = arr[Math.floor((end+... | Sliding Window Median |
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.
You may assume that you have a... | dfs(total) | class Solution {
public int coinChange(int[] coins, int amount) {
int m=coins.length,n=amount;
int dp[][]=new int[m+1][n+1];
for(int j=0;j<=n;j++){
dp[0][j]=0;
}
for(int i=0;i<=m;i++){
dp[i][0]=0;
}
for(int i=1;i<=m;i++){
... | dfs(total) | dfs(total) | Coin Change |
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example 1:
Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzz... | class Solution:
def totalNQueens(self, n: int) -> int:
res=0
#用于存放结果
pdia=set()
ndia=set()
col=set()
def backtrack(r):
#利用r作为一种计数,表示目前所在的行数
if r==n:
#判断已经完成棋盘,返回结果
nonlocal res
res+=1
... | class Solution {
int count = 0;
public int totalNQueens(int n) {
boolean col[] = new boolean[n];
boolean diag[] = new boolean[2*n-1];
boolean rdiag[] = new boolean[2*n-1];
countSolution(n,col, diag, rdiag, 0);
return count;
}
void countSolution(int n, boolean[] ... | class Solution {
public:
int totalNQueens(int n) {
vector<bool> col(n), diag(2*n-1), anti_diag(2*n-1);
return solve(col, diag, anti_diag, 0);
}
int solve(vector<bool>& col, vector<bool>& diag, vector<bool>& anti_diag, int row) {
int n = size(col), count = 0;
if(row == n) return 1;
for(int colum... | /**
* @param {number} n
* @return {number}
*/
var totalNQueens = function(n) {
// Keep track of columns with queens
const cols = new Set();
// Keep track of positive slope diagonal by storing row number + column number
const posDiag = new Set();
// Keep track of negative slope diagonal by storing row numb... | N-Queens II |
Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.
Example 1:
Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]
Output: [3,4]
Explanation:
The only integers present in each o... | class Solution:
def intersection(self, A: List[List[int]]) -> List[int]:
return sorted([k for k,v in Counter([x for l in A for x in l]).items() if v==len(A)])
| class Solution {
public List<Integer> intersection(int[][] nums) {
List<Integer> ans = new ArrayList<>();
int[] count = new int[1001];
for(int[] arr : nums){
for(int i : arr){
count[i]++;
}
}
for(int i=0;i<count.length;i++){
... | class Solution {
public:
vector<int> intersection(vector<vector<int>>& nums) {
int n = nums.size(); // gives the no. of rows
map<int,int> mp; // we don't need unordered_map because we need the elements to be in sorted format.
vector<int> vec;
// traverse through the 2D array... | var intersection = function(nums) {
let set = addToSet(nums[0]);
for(let i=1; i<nums.length; i++) {
let tempSet = addToSet(nums[i]);
for(let key of set) {
if( !tempSet.has(key) )
set.delete(key);
}
}
return [...set].sort( (a,b) => a-b );
};
function a... | Intersection of Multiple Arrays |
Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold.
Example 1:
Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respe... | class Solution:
def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
wstart = wsum = count = 0
for wend in range(len(arr)):
wsum += arr[wend]
if wend >= k:
wsum -= arr[wstart]
wstart += 1
if... | class Solution {
public int numOfSubarrays(int[] arr, int k, int threshold) {
int average=0,count=0,start=0,sum=0;
for(int i=0;i<arr.length;i++){
sum+=arr[i];
if(i>=k-1){
average=sum/k;
if(average>=threshold) count++;
sum... | class Solution {
public:
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
int i=0;int j=0;int sum=0;int ans=0;
while(j<arr.size()){
sum+=arr[j];
if(j-i+1<k) j++;
else if(j-i+1==k){
if(sum/k>=threshold){
ans++;
... | var numOfSubarrays = function(arr, k, threshold) {
let total = 0;
let left = 0;
let right = k;
// get initial sum of numbers in first sub array range, by summing left -> right
let sum = arr.slice(left, right).reduce((a, b) => a + b, 0);
while (right <= arr.length) {
// move through the a... | Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold |
You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string if it is generated by deleting some characters of a given string without c... | class Solution:
def removePalindromeSub(self, s: str) -> int:
return 1 if s[::-1] == s else 2
| class Solution
{
public int removePalindromeSub(String s)
{
int left = 0 , right = s.length() - 1 ;
while( left < right )
{
if( s.charAt(left++) != s.charAt(right--) )
{
return 2 ;
}
}
return 1 ;
}
} | //the major obersavation or we can also verify by giving your own test it always returns 1 or 2
//if the whole string is palindrom then return 1 if not then return 2.
class Solution {
static bool isPal(string s){
string p = s;
reverse(p.begin() , p.end());
return s==p;
}
public... | var removePalindromeSub = function(s) {
const isPalindrome = s == s.split('').reverse().join('');
return isPalindrome ? 1 : 2;
}; | Remove Palindromic Subsequences |
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them togeth... | class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
dp = collections.defaultdict(int)
dp[0] = 0
for x in rods:
nxt = dp.copy()
for d, y in dp.items():
# init state
# ------|----- d -----| # tall side
# - ... | class Solution {
public int tallestBillboard(int[] rods) {
int[] result = new int[1];
dfs(rods, 0, 0, 0, rods.length, result);
return result[0];
}
private void dfs(int[] rods, int left, int right, int level, int n, int[] result) {
if (level == n) {
if (left == rig... | class Solution {
public:
int f(int i,vector<int>& v, int a, int b){
if(i==v.size()){
if(a==b){
return a;
}
return 0;
}
int x = f(i+1,v,a,b);
int y = f(i+1,v,a+v[i],b);
int z = f(i+1,v,a,b+v[i]);
return max({x,y,z});
}
int tallestBillboard(vector<int>& rods) {
return f(0,rods,0,0);
}
}... | /**
* @param {number[]} rods
* @return {number}
*/
var tallestBillboard = function(rods) {
let len = rods.length;
if (len <= 1) return 0;
let dp = [];
for (let i = 0; i < len + 5; i++) {
dp[i] = [];
for (let j = 0; j < 5005 * 2; j++) {
dp[i][j] = -1
}
}
ret... | Tallest Billboard |
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform... | class Solution:
def canTransform(self, start: str, end: str) -> bool:
def chars(s):
for i, c in enumerate(s):
if c != 'X':
yield i, c
yield -1, ' '
for (startI, startC), (endI, endC) in zip(chars(start), chars(end)):
... | class Solution {
public boolean canTransform(String start, String end) {
int startL = 0, startR = 0;
int endL = 0, endR = 0;
String stLR = "", edLR = "";
for(int i = 0; i < start.length(); i++) {
if(start.charAt(i) != 'X') {
if(start.charAt(i) == 'L') {
... | class Solution {
public:
bool canTransform(string start, string end) {
int s=0,e=0;
while(s<=start.size() and e<=end.size()){
while(s<start.size() and start[s]=='X'){
s++;
}
while(e<end.size() and end[e]=='X'){
e++;
}
... | /**
* @param {string} start
* @param {string} end
* @return {boolean}
*/
var canTransform = function(start, end) {
let i = 0;
let j = 0;
while (i < start.length || j < end.length) {
if (start[i] === 'X') {
i++;
continue;
}
if (end[j] === 'X') {
... | Swap Adjacent in LR String |
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
Example 1:
Input: points = [[1,1],[2,2],[3,3]]
Output: 3
Example 2:
Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Constr... | class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
ans = 0
n = len(points)
for i in range(n):
d = collections.defaultdict(int)
for j in range(n):
if i != j:
slope = float("inf")
if (poi... | class Solution {
public int maxPoints(int[][] points) {
int n = points.length;
if(n == 1) return n;
int result = 0;
for(int i = 0; i< n; i++){
for(int j = i+1; j< n; j++){
result = Math.max(result, getPoints(i, j, points));
}
}
... | class Solution {
public:
//DP solution
//TC-O(N*N)
//SC- ~ O(N*N)
//Custom Sort
bool static cmp(vector<int> p1,vector<int> p2){
if(p1[0]==p2[0])
return p1[1]<p2[1];
return p1[0]<p2[0];
}
//Slope Calculating
float calcSlope(int x1,int y1,int x2,int y2){
... | /**
* @param {number[][]} points
* @return {number}
*/
var maxPoints = function(points) {
if (points.length === 1) {
return 1;
}
const slopes = {};
let dx, dy;
let xbase, ybase;
let xref, yref, key;
const INFINITE_SLOPE = 'infinite';
for(let i = 0; i < points.length... | Max Points on a Line |
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
In... | class Solution(object):
def numberOfSubarrays(self, nums, k):
"""
e.g. k = 2
nums = [2, 2, 1, 2, 1, 2, 2]
index= 0 1 2 3 4 5 6
2 even numbers to left of first 1
2 even numbers to right of last 1
total number of subarrays = pick between 0-2 numbers on left, then, pick between 0-2 numbers on right
... | class Solution {
public int numberOfSubarrays(int[] nums, int k) {
int i = 0;
int j = 0;
int odd = 0;
int result = 0;
int temp = 0;
/*
Approach : two pointer + sliding window technique
step 1 : we have fix i and moving j until our count of od... | class Solution {
public:
vector<int> nums;
int solve(int k){
int low = 0, high = 0, cnt = 0, res = 0;
while(high < nums.size()){
if(nums[high] & 1){
cnt++;
while(cnt > k){
if(nums[low] & 1) cnt--;
low++;
... | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var numberOfSubarrays = function(nums, k) {
const len = nums.length;
const pre = new Array(len).fill(-1);
const post = new Array(len).fill(len);
let lastOcc = -1;
for(let i = 0; i < len; i++) {
pre[i] = lastOcc;
... | Count Number of Nice Subarrays |
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer n an... | class Solution:
def countPaths(self, n: int, roads: List[List[int]]) -> int:
graph = defaultdict(dict)
for u, v, w in roads:
graph[u][v] = graph[v][u] = w
dist = {i:float(inf) for i in range(n)}
ways = {i:0 for i in range(n)}
dist[0], ways[0] = 0, 1
heap =... | class Solution {
class Pair{
int node;
int dist;
Pair(int node , int dist){
this.node = node;
this.dist = dist;
}
}
public int countPaths(int n, int[][] roads) {
int mod = (int)Math.pow(10 , 9) + 7;
ArrayList<ArrayList<Pair>> adj = new ... | class Solution {
public:
int countPaths(int n, vector<vector<int>>& roads) {
int mod = 1e9+7;
vector<vector<pair<int, int>>> graph(n);
for(auto &road: roads) {
graph[road[0]].push_back({road[1], road[2]});
graph[road[1]].push_back({road[0], road[2]});
}
... | /**
* @param {number} n
* @param {number[][]} roads
* @return {number}
*/
var countPaths = function(n, roads) {
let adj = {}, dist = Array(n).fill(Infinity), minHeap = new MinHeap(), count = Array(n).fill(1);
//CREATE ADJ MATRIX
for(let [from, to , weight] of roads){
adj[from] = adj[from] || []... | Number of Ways to Arrive at Destination |
You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,
If isLefti == 1, then childi is the left child of parenti.
If isLefti == 0, then childi is the right child of parenti.
Con... | class Solution:
def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
hashmap = {}
nodes = set()
children = set()
for parent,child,isLeft in descriptions:
nodes.add(parent)
nodes.add(child)
children.add(child)
... | class Solution {
public TreeNode createBinaryTree(int[][] descriptions) {
HashMap<Integer,TreeNode> map=new HashMap<>();
HashSet<Integer> children=new HashSet<>();
for(int[] info:descriptions)
{
int parent=info[0],child=info[1];
boolean isLeft=info[2]==1?true:... | class Solution {
public:
TreeNode* createBinaryTree(vector<vector<int>>& descriptions){
unordered_map<int, TreeNode*> getNode; //to check if node alredy exist
unordered_map<int, bool> isChild; //to check if node has parent or not
for(auto &v: descriptions){
if(getNode.count(v[0])... | var createBinaryTree = function(descriptions) {
let nodes = new Map(), children = new Set();
for (let [parent, child, isLeft] of descriptions) {
let parentNode = nodes.get(parent) || new TreeNode(parent);
if (!nodes.has(parent)) nodes.set(parent, parentNode);
let childNode = nodes.get(child) || new Tre... | Create Binary Tree From Descriptions |
Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).
Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.
Example 1... | class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
F = favoriteCompanies
ans = []
seen = set()
for i in range(len(F)):
for j in range(i+1,len(F)):
st1 = set(F[i])
st2 = set... | class Solution {
public List<Integer> peopleIndexes(List<List<String>> favoriteCompanies) {
Set<String>[] fav = new Set[favoriteCompanies.size()];
Set<Integer> set = new HashSet<>();
for (int i = 0; i < favoriteCompanies.size(); i++) {
set.add(i);
fav[i] = new HashSet... | /*
* author: deytulsi18
* problem: https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/
* time complexity: O(n*n*m)
* auxiliary space: O(1)
* language: cpp
*/
class Solution {
public:
bool isSubset(vector<string> &b, vector<string> &a)
{
return (inc... | var peopleIndexes = function(favoriteCompanies) {
let arr = favoriteCompanies
let len = arr.length
let ret = []
for(let i = 0; i < len; i++) {
let item1 = arr[i]
let isSubset = false
for(let j = 0; j < len; j++) {
if(i === j) continue
let item2 = arr[j]
... | People Whose List of Favorite Companies Is Not a Subset of Another List |
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1
Example 2:
Input: text = "l... | class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
freq = {'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0}
for char in text:
if not char in freq:
continue
step = 0.5 if char == 'l' or char == 'o' else 1
... | class Solution {
public int maxNumberOfBalloons(String text) {
return maxNumberOfWords(text, "balloon");
}
private int maxNumberOfWords(String text, String word) {
final int[] tFrequencies = new int[26];
for (int i = 0; i < text.length(); ++i) {
tFrequencies[text.charAt... | class Solution {
public:
int maxNumberOfBalloons(string text) {
map<char,int>m;
for(int i=0;i<text.length();i++)
{
m[text[i]]++;
}
string s="balloon";
int flag=1;
int c=0;
while(1)
{
for(int i=0;i<s.length();i++)
... | /**
* @param {string} text
* @return {number}
*/
var maxNumberOfBalloons = function(text) {
// 1. create hashmap with "balloon" letters
// 2. keep track of how many letters in text belong to "balloon"
// 3. account for fact that we need two "l" and "o" per "balloon" instance
// 4. then select all map va... | Maximum Number of Balloons |
Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.
Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any... | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
m = len(board)
n = len(board[0])
res = 0
pole = [ [True for i in range(n)] for j in range(m) ]
for i in range(m):
for j in range(n):
if board[i][j... | class Solution {
public int countBattleships(char[][] board) {
int result = 0;
for(int i = 0;i<board.length;i++)
{
for(int j = 0;j<board[i].length;j++)
{
if(board[i][j] == 'X')
{
remov... | class Solution {
public:
bool isSafe(int i,int j,int r,int c,vector<vector<char>> &arr,vector<vector<bool>> &visited){
if(i<0 || i>r || j<0 || j>c){
return false;
}
// cout<<arr[i][j]<<" ";
if(arr[i][j]!='X'){
return false;
}
if(arr[i][j]... | var countBattleships = function(board) {
let count = 0;
for(let rowIndex = 0; rowIndex < board.length; rowIndex++){
for(let columnIndex = 0; columnIndex < board[rowIndex].length; columnIndex++){
const isTopEmpty = rowIndex === 0 || board[rowIndex - 1][columnIndex] !== "X";
... | Battleships in a Board |
Given an array arr that represents a permutation of numbers from 1 to n.
You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1.
You are also given an integer m. Find the... | class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
n = len(arr)
ans = -1
if n == m: return m #just in case
# make in "inverted" array with artificial ends higher then everything between
sor= [0 for _ in range(n+2)]
for i in range(n):
... | class Solution {
int[] par, size, count, bits;
// par: parent array, tells about whose it the parent of ith element
// size: it tells the size of component
// count: it tells the count of islands (1111 etc) of size i;
// count[3] = 4: ie -> there are 4 islands of size 3
public int find(... | class Solution {
public:
int findLatestStep(vector<int>& arr, int m) {
int n=size(arr),ans=-1;
vector<int>cntL(n+2),indL(n+2);
for(int i=0;i<n;i++){
int li=indL[arr[i]-1],ri=indL[arr[i]+1],nl=li+ri+1;
indL[arr[i]]=nl;
indL[arr[i]-li]=nl;
indL[a... | var findLatestStep = function(arr, m) {
if (m === arr.length) return arr.length
let bits = new Array(arr.length+1).fill(true), pos, flag, i, j
for (i = arr.length - 1, bits[0] = false; i >= 0; i--) {
pos = arr[i], bits[pos] = false
for (j = 1, flag = true; flag && j <= m; j++) flag = bits[po... | Find Latest Group of Size M |
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node ... | # 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 convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
ans = []
def inorder(n... | class Solution {
public TreeNode convertBST(TreeNode root) {
if(root!=null) {
List<Integer> nodesValues = new ArrayList<>();
helperNodesVales(root, nodesValues);
traverseAndAdd(root, nodesValues);
return root;
}
return null;
}
private void helperNodesVales... | class Solution {
public:
int val = 0;
TreeNode* convertBST(TreeNode* root) {
if(root)
{
convertBST(root->right); // traverse right sub-tree
val += root->val; // add val
root->val = val; // update val
convertBST(root->left); // traverse left sub-tr... | var convertBST = function(root) {
let sum = 0;
const go = (node) => {
if (!node) return;
go(node.right);
sum += node.val;
node.val = sum;
go(node.left);
}
go(root);
return root;
}; | Convert BST to Greater Tree |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.