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 |
|---|---|---|---|---|---|
There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all t... | from collections import defaultdict
from itertools import accumulate
class Solution:
def stoneGameV(self, stoneValue: List[int]) -> int:
n = len(stoneValue)
dp = [[0]*n for _ in range(n)]
left = [[0]*n for _ in range(n)]
prefix = list(accumulate(stoneValue))
prefix = [0]+pr... | class Solution {
int dp[][];
public int fnc(int a[], int i, int j, int sum){
//System.out.println(i+" "+j);
int n=a.length;
if(i>j)
return 0;
if(j>n)
return 0;
if(i==j){
dp[i][j]=-1;
return 0;
}
if(dp[i][j]!=... | class Solution {
public:
int dp[501][501];
int f(vector<int> &v,int i,int j){
if(i>=j) return 0;
if(dp[i][j]!=-1) return dp[i][j];
int r=0;
for(int k=i;k<=j;k++) r+=v[k];
int l=0,ans=0;
for(int k=i;k<=j;k++){
l+=v[k];
r-=v[k];
... | var stoneGameV = function(stoneValue) {
// Find the stoneValue array's prefix sum
let prefix = Array(stoneValue.length).fill(0);
for (let i = 0; i < stoneValue.length; i++) {
prefix[i] = stoneValue[i] + (prefix[i - 1] || 0);
}
let dp = Array(stoneValue.length).fill().map(() => Array(stoneVa... | Stone Game V |
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2x.
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 24 = 16
Example 3:
Input: n = 3
Ou... | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0: return False
k = n
while k != 1:
if k % 2 != 0:
return False
k = k // 2
return True
count = 0
for i in range(... | class Solution {
public boolean isPowerOfTwo(int n) {
return power2(0,n);
}
public boolean power2(int index,int n){
if(Math.pow(2,index)==n)
return true;
if(Math.pow(2,index)>n)
return false;
return power2(index+1,n);
}
} | class Solution {
public:
bool isPowerOfTwo(int n) {
if(n==0) return false;
while(n%2==0) n/=2;
return n==1;
}
}; | var isPowerOfTwo = function(n) {
let i=1;
while(i<n){
i*=2
}return i===n
}; | Power of Two |
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 all distinct solutions to the n-queens puzzle. You may return the answer in any order.
Each solution contains a distinct board configuration of the n-queens' placement, w... | class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
coord = self.findNextRows(0, n)
ans = []
for c in coord:
temp = []
for j in c:
temp.append("."*j+"Q"+"."*(n-j-1))
ans.append(temp)
return ans
... | Simple backtracking logic, try out each row and col and check position is valid or not.
since we are going row one by one, there is no way queen is placed in that row.
so, we need to check col, diagonals for valid position.
// col is straightforward flag for each column
// dia1
// 0 1 2 3
// 1 2 3 4
// 2 3 4 5
// 3... | class Solution {
bool isSafe(vector<string> board, int row, int col, int n){
int r=row;
int c=col;
// Checking for upper left diagonal
while(row>=0 && col>=0){
if(board[row][col]=='Q') return false;
row--;
col--;
}
... | // time O(n!) | space O(n^n)
var solveNQueens = function(n) {
let res = [];
function backtrack(board, r) {
if (r === n) {
// - 1 to account for adding a Q that takes up a space
res.push(board.map((c) => '.'.repeat(c) + 'Q' + '.'.repeat(n - c - 1)));
return;
... | N-Queens |
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.
There may be duplicates in the original array.
Note: An array A rotated by x positions results in an array B of the same length such that A[i] =... | class Solution:
def check(self, num: List[int]) -> bool:
ct=0
for i in range(1,len(num)):
if num[i-1]>num[i]:
ct+=1
if num[len(num)-1]>num[0]:
ct+=1
return ct<=1 | class Solution {
public boolean check(int[] nums) {
// here we compare all the neighbouring elemnts and check whether they are in somewhat sorted
// there will be a small change due to rotation in the array at only one place.
// so if there are irregularities more than once, return false
... | class Solution {
public:
bool check(vector<int>& nums) {
int count=0;
for(int i=0;i<nums.size();i++){
if(nums[i]>nums[(i+1)%nums.size()])
count++;
}
return (count<=1);
}
}; | var check = function(nums) {
let decreased = false
for (let i = 1; i < nums.length; i += 1) {
if (nums[i] < nums[i - 1]) {
if (decreased) {
return false
}
decreased = true
}
}
return decreased ? nums[0] >= nums[nums.length - 1] : true
}; | Check if Array Is Sorted and Rotated |
Given an m x n binary matrix mat, return the number of special positions in mat.
A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).
Example 1:
Input: mat = [[1,0,0],[0,0,1],[1,0,0]]
Output: 1
Explanation: (1, 2) is a speci... | class Solution(object):
def numSpecial(self, mat):
"""
:type mat: List[List[int]]
:rtype: int
"""
r=len(mat)
c=len(mat[0])
r_c={}
l_c={}
for i in range(r):
flag=0
for j in range(c):
if(m... | class Solution {
public int numSpecial(int[][] mat) {
int count=0;
for(int i=0;i<mat.length;i++){
for(int j=0;j<mat[0].length;j++){
if(mat[i][j]==1){
int flag=0;
for(int k=0;k<mat.length;k++){
if(mat[k][j]!=0 &... | class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {
vector<vector<int>>v;
map<int,vector<int>>m;
for(int i=0;i<mat.size();i++){
vector<int>temp = mat[i];
for(int j=0;j<temp.size();j++){
m[j].push_back(temp[j]);
}
}... | /**
* @param {number[][]} mat
* @return {number}
*/
var numSpecial = function(mat) {
let specialPostions = [];
for(let i in mat){
for(let j in mat[i]){
if(mat[i][j] == 1 ){
let horizontalOnes = 0;
let verticalOnes = 0;
f... | Special Positions in a Binary Matrix |
Design your implementation of the circular double-ended queue (deque).
Implement the MyCircularDeque class:
MyCircularDeque(int k) Initializes the deque with a maximum size of k.
boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.
boolean inse... | class MyCircularDeque {
public:
deque<int> dq;
int max_size;
MyCircularDeque(int k) {
max_size = k;
}
bool insertFront(int value) {
if(dq.size() < max_size)
{
dq.push_front(value);
return true;
... | class MyCircularDeque {
public:
deque<int> dq;
int max_size;
MyCircularDeque(int k) {
max_size = k;
}
bool insertFront(int value) {
if(dq.size() < max_size)
{
dq.push_front(value);
return true;
... | class MyCircularDeque {
public:
deque<int> dq;
int max_size;
MyCircularDeque(int k) {
max_size = k;
}
bool insertFront(int value) {
if(dq.size() < max_size)
{
dq.push_front(value);
return true;
}
return false;
}
bool in... | class MyCircularDeque {
public:
deque<int> dq;
int max_size;
MyCircularDeque(int k) {
max_size = k;
}
bool insertFront(int value) {
if(dq.size() < max_size)
{
dq.push_front(value);
return true;
... | Design Circular Deque |
The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.
For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.
Given an array nums, return the sum of all XOR totals for every subset of nums.
Note: Subsets with the same elements should be counte... | class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
def sums(term, idx):
if idx == len(nums):
return term
return sums(term, idx + 1) + sums(term ^ nums[idx], idx + 1)
return sums(0, 0) | class Solution {
int sum=0;
public int subsetXORSum(int[] nums) {
sum=0;
return getAns(nums,0,0);
}
int getAns(int[] arr,int i,int cur){
if(i==arr.length){
return cur;
}
return getAns(arr,i+1,cur^arr[i]) + getAns(arr,i+1,cur);
}
} | class Solution {
public:
int subsetXORSum(vector<int>& nums)
{
int ans=0;
for(int i=0; i<32; i++)
{
int mask=1<<i;
int count=0;
for(int j=0; j<nums.size(); j++)
{
if(nums[j]&mask) count++;
}
if(count... | var subsetXORSum = function(nums) {
let output=[];
backtrack();
return output.reduce((a,b)=>a+b);
function backtrack(start = 0, arr=[nums[0]]){
output.push([...arr].reduce((a,b)=>a^b,0));
for(let i=start; i<nums.length; i++){
arr.push(nums[i]);
backtrack(i+1, arr);
... | Sum of All Subset XOR Totals |
You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.
Choose at most k different engineers out of the n engineers to form a team with th... | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
l = list(zip(efficiency,speed))
l.sort(reverse=True)
h = []
res = 0
mod = 1000000007
mx_sum = 0
print(l)
for i in range(n):
res = max(... | class Engineer {
int speed, efficiency;
Engineer(int speed, int efficiency) {
this.speed = speed;
this.efficiency = efficiency;
}
}
class Solution {
public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {
List<Engineer> engineers = new ArrayList<>();
for... | class Solution {
public:
int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
long long sum = 0, ans = 0;
const int m = 1e9 + 7;
vector<vector<int>> pairs(n, vector<int> (2, 0));
for(int i = 0;... | var maxPerformance = function(n, speed, efficiency, k) {
let ord = Array.from({length: n}, (_,i) => i)
ord.sort((a,b) => efficiency[b] - efficiency[a])
let sppq = new MinPriorityQueue(),
totalSpeed = 0n, best = 0n
for (let eng of ord) {
sppq.enqueue(speed[eng])
if (sppq.size() <=... | Maximum Performance of a Team |
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).
There are n + 1 taps located at points [0, 1, ..., n] in the garden.
Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th... | class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:
maxRanges = [0]
for i in range(len(ranges)):
minIdx = max(i - ranges[i], 0)
maxIdx = min(i + ranges[i], n)
idx = bisect_left(maxRanges, minIdx)
if idx == len(maxRanges) or maxIdx <= m... | class Solution {
public int minTaps(int n, int[] ranges) {
Integer[] idx = IntStream.range(0, ranges.length).boxed().toArray(Integer[]::new);
Arrays.sort(idx, Comparator.comparingInt(o -> o-ranges[o]));
int ans = 1, cur = 0, end = 0;
for (int i = 0;i<ranges.length&&end<n;i++){
... | class Solution {
public:
int minTaps(int n, vector<int>& ranges) {
vector<pair<int,int>> v;
for(int i=0;i<ranges.size();i++){
// making ranges
v.push_back({i-ranges[i],i+ranges[i]});
}
// sorting the intervals
sort(v.begin(),v.end());
... | var minTaps = function(n, ranges) {
let intervals = [];
for (let i = 0; i < ranges.length; i++) {
let l = i - ranges[i];
let r = i + ranges[i];
intervals.push([l, r]);
}
intervals.sort((a, b) => {
if (a[0] === b[0]) return b[1] - a[1];
return a[0] - b[0];
})
... | Minimum Number of Taps to Open to Water a Garden |
Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.
Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer,... | class Solution:
def nextGreaterElement(self, n):
digits = list(str(n))
i = len(digits) - 1
while i-1 >= 0 and digits[i] <= digits[i-1]:
i -= 1
if i == 0: return -1
j = i
while j+1 < len(digits) and digits[j+1] > digits[i-1]:
... | class Solution {
public int nextGreaterElement(int n) {
char[] arr = (n + "").toCharArray();
int i = arr.length - 1;
while(i > 0){
if(arr[i-1] >= arr[i]){
i--;
}else{
break;
}
}
if(i == 0){
... | class Solution {
public:
int nextGreaterElement(int n) {
vector<int>vec;
int temp = n;
while(n>0){
int r = n%10;
vec.push_back(r);
n /= 10;
}
sort(vec.begin(),vec.end());
do{
int num=0;
long j=0;
i... | var nextGreaterElement = function(n) {
const MAX_VALUE = 2 ** 31 - 1;
const nums = `${n}`.split('');
let findPos;
for (let index = nums.length - 2; index >= 0; index--) {
if (nums[index] < nums[index + 1]) {
findPos = index;
break;
}
}
if (findPos === undefined) return -1;
for (let index = nums.lengt... | Next Greater Element III |
There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience... | class Solution:
def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:
#Build Adjency List
adjList = defaultdict(list)
for source, target in edges:
adjList[source].append(target)
adjList[target].append(source)
#BFS to get the shor... | class Solution {
public int networkBecomesIdle(int[][] edges, int[] patience) {
int n = patience.length;
// creating adjacency list
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i = 0 ; i < n ; i++ ) {
adj.add(new ArrayList<>());
}
for(i... | class Solution {
public:
int networkBecomesIdle(vector<vector<int>>& edges, vector<int>& patience) {
int n = patience.size();
vector <vector <int>> graph(n);
vector <int> time(n, -1);
for(auto x: edges) { // create adjacency list
graph[x[0]].push_back(x[1]);
... | /**
* @param {number[][]} edges
* @param {number[]} patience
* @return {number}
*/
var networkBecomesIdle = function(edges, patience) {
/*
Approach:
Lets call D is the distance from node to master
And last message sent from node is at T
Then last message will travel till D+T and network will be idal at D+... | The Time When the Network Becomes Idle |
There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.
The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is... | class Solution:
def maximalNetworkRank(self, n: int, roads) -> int:
max_rank = 0
connections = {i: set() for i in range(n)}
for i, j in roads:
connections[i].add(j)
connections[j].add(i)
for i in range(n - 1):
for j in range(i + 1, n):
... | class Solution {
public int maximalNetworkRank(int n, int[][] roads) {
//number of road connected to city
int[] numRoadsConnectedCity = new int[100 + 1];
//road exist between two two cities
boolean[][] raadExist = new boolean[n][n];
for(int[] cities... | class Solution {
public:
int maximalNetworkRank(int n, vector<vector<int>>& roads) {
vector<vector<int>>graph(n,vector<int>(n,0));
vector<int>degree(n,0);
for(int i=0;i<roads.size();i++){
int u=roads[i][0];
int v=roads[i][1];
degree[u]++;
degre... | var maximalNetworkRank = function(n, roads) {
let res = 0
let map = new Map()
roads.forEach(([u,v])=>{
map.set(u, map.get(u) || new Set())
let set = map.get(u)
set.add(v)
map.set(v, map.get(v) || new Set())
set = map.get(v)
set.add(u)
})
... | Maximal Network Rank |
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints:
-100.... | class Solution:
def myPow(self, x: float, n: int) -> float:
self.x = x
if n == 0:
return 1
isInverted = False
if n < 0:
isInverted = True
n = -1 * n
result = self.pow(n)
return result if not isInverted el... | class Solution {
public double myPow(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
else if (n == -1) return 1 / x;
double res = myPow(x, n / 2);
if (n % 2 == 0) return res * res;
else if (n % 2 == -1) return res * res * (1/x);
else return res ... | class Solution {
public:
double myPow(double x, int n) {
if(n==0) return 1; //anything to the power 0 is 1
if(x==1 || n==1) return x; //1 to the power anything = 1 or x to the power 1 = x
double ans = 1;
long long int a = abs(n); //since in... | var myPow = function(x, n) {
return x**n;
}; | Pow(x, n) |
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Ea... | #pattern
actual update ref
0 0 0
1 1 1
0 1 -1
1 0 -2
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
r = len(board)
c = len(board[0])
ans = [[0]*c for _ in range(r)]
neighs = [[1,0],[-1,0],[0,1],[0,-1],[-1... | class Solution {
public void gameOfLife(int[][] board) {
int m = board.length, n = board[0].length;
int[][] next = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
next[i][j] = nextState(board, i, j, m, n);
}
}
... | // Idea: Encode the value into 2-bit value, the first bit is the value of next state, and the second bit is the value of current state
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
int n = board[0].size();
for (int i=0; i<m; ++i) {
f... | /**
* @param {number[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var gameOfLife = function(board) {
const m = board.length, n = board[0].length;
let copy = JSON.parse(JSON.stringify(board));
const getNeighbor = (row, col) => {
let radius = [-1, 0, 1], co... | Game of Life |
You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way:
nums[0] = 0
nums[1] = 1
nums[2 * i] = nums[i] when 2 <= 2 * i <= n
nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n
Return the maximum integer in the array nums.
E... | class Solution:
def getMaximumGenerated(self, n):
nums = [0]*(n+2)
nums[1] = 1
for i in range(2, n+1):
nums[i] = nums[i//2] + nums[(i//2)+1] * (i%2)
return max(nums[:n+1]) | class Solution {
public int getMaximumGenerated(int n) {
if(n==0 || n==1) return n;
int nums[]=new int [n+1];
nums[0]=0;
nums[1]=1;
int max=Integer.MIN_VALUE;
for(int i=2;i<=n;i++){
if(i%2==0){
nums[i]=nums[i/2];
}
... | class Solution {
public:
int getMaximumGenerated(int n) {
// base cases
if (n < 2) return n;
// support variables
int arr[n + 1], m;
arr[0] = 0, arr[1] = 1;
// building arr
for (int i = 2; i <= n; i++) {
if (i % 2) arr[i] = arr[i / 2] + arr[i / 2 +... | var getMaximumGenerated = function(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let arr = [0, 1];
let max = 0;
for (let i = 0; i < n; i++) {
if (2 <= 2 * i && 2 * i <= n) {
arr[2 * i] = arr[i]
if (arr[i] > max) max = arr[i];
}
if (2 <= 2 * i && 2... | Get Maximum in Generated Array |
There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.
For each location indices[i], do both of the following:
Increment all the cells on row ri.
Increment all the... | class Solution:
def oddCells(self, row: int, col: int, indices: List[List[int]]) -> int:
rows, cols = [False] * row, [False] * col
for index in indices:
rows[index[0]] = not rows[index[0]]
cols[index[1]] = not cols[index[1]]
count = 0
for i in rows:
... | // --------------------- Solution 1 ---------------------
class Solution {
public int oddCells(int m, int n, int[][] indices) {
int[][] matrix = new int[m][n];
for(int i = 0; i < indices.length; i++) {
int row = indices[i][0];
int col = indices[i][1];
... | static int x = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0; }();
class Solution { // tc: O(n+m) & sc: O(n+m)
public:
int oddCells(int n, int m, vector<vector<int>>& indices) {
vector<bool> rows(n,false),cols(m,false);
for(auto index: indices){
rows[index[0]] = ro... | var oddCells = function(m, n, indices) {
const matrix = Array.from(Array(m), () => Array(n).fill(0));
let res = 0;
for (const [r, c] of indices) {
for (let i = 0; i < n; i++) {
// toggle 0/1 for even/odd
// another method: matrix[r][i] = 1 - matrix[r][i]
// or: m... | Cells with Odd Values in a Matrix |
You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums, and that the score is not necessarily an integer.
Return the maxi... | class Solution:
def largestSumOfAverages(self, A, k):
n = len(A)
dp = [0] * n
sum = 0
for i in range(n-1,-1,-1):
sum += A[i]
dp[i] = sum / (n-i)
for l in range(1,k):
for i in range(n-l):
sum = 0
for j in rang... | class Solution {
Double dp[][][];
int n;
int k1;
public double check(int b, int c,long sum,int n1,int ar[]){
System.out.println(b+" "+c);
if(dp[b][c][n1]!=null)
return dp[b][c][n1];
if(b==n){
if(sum!=0)
return (double)sum/(double)n1;
... | class Solution {
public:
double solve(vector<int>&nums, int index, int k, vector<vector<double>>&dp){
if(index<0)
return 0;
if(k<=0)
return -1e8;
if(dp[index][k]!=-1)
return dp[index][k];
double s_sum = 0;
double maxi = INT_MIN;
i... | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var largestSumOfAverages = function(nums, k) {
// set length
const len = nums.length;
// set sum by len fill
const sum = new Array(len).fill(0);
// set nums first to first of sum
sum[0] = nums[0];
// set every item o... | Largest Sum of Averages |
You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or num... | class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
dp = [[-1] * len(nums) for _ in nums]
def get_score(i: int, j: int) -> int:
if i == j:
dp[i][j] = 0
return dp[i][j]
if i == j - 1:
dp[i][j] = nums[j] if nums[... | class Solution {
public boolean PredictTheWinner(int[] nums) {
return predictTheWinner(nums, 0, nums.length-1,true,0, 0);
}
private boolean predictTheWinner(int[] nums, int start,int end, boolean isP1Turn, long p1Score, long p2Score){
if(start > end){
return p1Score >= p2Score;
... | class Solution {
public:
bool PredictTheWinner(vector<int>& nums) {
vector<vector<vector<int>>> dp(nums.size(),vector<vector<int>>(nums.size(),vector<int>(3,INT_MAX)));
int t=fun(dp,nums,0,nums.size()-1,1);
return t>=0;
}
int fun(vector<vector<vector<int>>>& dp,vector<int>& v,int i,i... | var PredictTheWinner = function(nums) {
const n = nums.length;
const dp = [];
for (let i = 0; i < n; i++) {
dp[i] = new Array(n).fill(0);
dp[i][i] = nums[i];
}
for (let len = 2; len <= n; len++) {
for (let start = 0; start < n - len + 1; start++) {
const end = s... | Predict the Winner |
You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
The value of the first element in arr must be 1.
The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) &l... | class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
counter = collections.Counter(arr)
available = sum(n > len(arr) for n in arr)
i = ans = len(arr)
while i > 0:
# This number is not in arr
if not counter[i]:
... | class Solution {
public int maximumElementAfterDecrementingAndRearranging(int[] arr) {
Arrays.sort(arr);
arr[0] = 1;
for(int i = 1;i<arr.length;i++){
if(Math.abs(arr[i] - arr[i-1]) > 1)
arr[i] = arr[i-1] + 1;
}
return arr[arr.length-1];
}
} | class Solution {
public:
int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {
sort(arr.begin(),arr.end());
int n=arr.size();
arr[0]=1;
for(int i=1;i<n;i++)
{
if(arr[i]-arr[i-1]>1)
{
arr[i]=arr[i-1]+1;
}
... | var maximumElementAfterDecrementingAndRearranging = function(arr) {
if (!arr.length) return 0
arr.sort((a, b) => a - b)
arr[0] = 1
for (let i = 1; i < arr.length; i++) {
if (Math.abs(arr[i] - arr[i - 1]) > 1) arr[i] = arr[i - 1] + 1
}
return arr.at(-1)
}; | Maximum Element After Decreasing and Rearranging |
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1]
Output: [[1]]
&nbs... | class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return list(permutations(nums)) | class Solution {
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> permute(int[] nums) {
ArrayList<Integer> list = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
backTrack(nums, list, visited);
return res;
}
private void backTra... | class Solution {
public:
void per(int ind, int n, vector<int>&nums, vector<vector<int>> &ans)
{
if(ind==n)
{
ans.push_back(nums);
return;
}
for(int i=ind;i<n;i++)
{
swap(nums[ind],nums[i]);
per(ind+1,n,nums,ans);
... | var permute = function(nums) {
const output = [];
const backtracking = (current, remaining) => {
if (!remaining.length) return output.push(current);
for (let i = 0; i < remaining.length; i++) {
const newCurrent = [...current];
const newRemaining = [...remaining];
... | Permutations |
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in an ascending order, return compute the researcher's h-index.
According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n paper... | import bisect
class Solution:
def hIndex(self, citations: List[int]) -> int:
n = len(citations)
for h in range(n, -1, -1):
if h <= n - bisect.bisect_left(citations, h):
return h | class Solution {
public int hIndex(int[] citations) {
int n=citations.length;
int res=0;
for(int i=0;i<n;i++)
{
if(citations[i]>=n-i)
{
return n-i;
}
}
return res;
}
} | class Solution {
public:
int hIndex(vector<int>& citations) {
int start = 0 , end = citations.size()-1;
int n = citations.size();
while(start <= end){
int mid = start + (end - start) / 2;
int val = citations[mid];
if(val == (n - mid)) return citations[mid]... | /**
* The binary search solution.
*
* Time Complexity: O(log(n))
* Space Complexity: O(1)
*
* @param {number[]} citations
* @return {number}
*/
var hIndex = function(citations) {
const n = citations.length
let l = 0
let r = n - 1
while (l <= r) {
const m = Math.floor((l + r) / 2)
if (citations[m] ... | H-Index II |
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each nod... | def cloneGraph(self, node: 'Node') -> 'Node':
if node == None:
return None
new_node = Node(node.val, [])
visited = set()
q = [[node, new_node]]
visited.add(node.val)
adj_map = {}
adj_map[node] =... | /*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> ... | 'IF YOU LIKE IT THEN PLS UpVote😎😎😎'
class Solution {
public:
Node* dfs(Node* cur,unordered_map<Node*,Node*>& mp)
{
vector<Node*> neighbour;
Node* clone=new Node(cur->val);
mp[cur]=clone;
for(auto it:cur->neighbors)
... | var cloneGraph = function(node) {
if(!node)
return node;
let queue = [node];
let map = new Map();
//1. Create new Copy of each node and save in Map
while(queue.length) {
let nextQueue = [];
for(let i = 0; i < queue.length; i++) {
let n = queue... | Clone Graph |
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
|a - x| < |b - x|, or
|a - x| == |b - x| and a < b
Example 1:
Input: arr = [1,2,3,4,5], k = ... | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
def sorted_distance(value, static_input = x):
return abs(value - static_input)
distances = []
result = []
heapq.heapify(distances)
for l,v in enu... | class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> result = new ArrayList<>();
int low = 0, high = arr.length -1;
while(high - low >= k){
if(Math.abs(arr[low] - x) > Math.abs(arr[high] - x))
low++;
else
high--;
}
... | class Solution {
public:
static bool cmp(pair<int,int>&p1,pair<int,int>&p2)
{
if(p1.first==p2.first) //both having equal abs diff
{
return p1.second<p2.second;
}
return p1.first<p2.first;
}
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
... | var findClosestElements = function(arr, k, x) {
const result = [...arr];
while (result.length > k) {
const start = result[0];
const end = result.at(-1);
x - start <= end - x
? result.pop()
: result.shift();
}
return result;
}; | Find K Closest Elements |
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater's warm radius range.
Given the positions of houses and heaters on a horizontal line, return the minimum radius... | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
"""
"""
houses.sort()
heaters.sort()
max_radius = -inf
for house in houses:
i = bisect_left(heaters, house)
if i == len(heaters):
max_radiu... | class Solution {
public boolean can(int r, int[] houses, int[] heaters) {
int prevHouseIdx = -1;
for(int i = 0; i < heaters.length; i++) {
int from = heaters[i]-r;
int to = heaters[i]+r;
for(int j = prevHouseIdx+1; j < houses.length; j++){
if(houses[j]<=to && houses[j]>=from){
... | class Solution {
public:
//we will assign each house to its closest heater in position(by taking the minimum
//of the distance between the two closest heaters to the house) and then store the maximum
//of these differences(since we want to have the same standard radius)
int findRadius(vector<int>& house... | var findRadius = function(houses, heaters) {
houses.sort((a, b) => a - b);
heaters.sort((a, b) => a - b);
let heaterPos = 0;
const getRadius = (house, pos) => Math.abs(heaters[pos] - house);
return houses.reduce((radius, house) => {
while (
heaterPos < heaters.length &&
getRadius(house, heaterPos) >=
... | Heaters |
Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:
Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
Pick a non-empty suffix from the string s where all the characters in this s... | class Solution:
def minimumLength(self, s: str) -> int:
while(len(s)>1 and s[0]==s[-1]):
s=s.strip(s[0])
else:
return len(s) | class Solution {
public int minimumLength(String s) {
int length = s.length();
char[] chars = s.toCharArray();
for(int left = 0,right = chars.length-1;left < right;){
if(chars[left] == chars[right]){
char c = chars[left];
while(left < right && chars[l... | class Solution {
public:
int minimumLength(string s) {
int i=0,j=s.length()-1;
while(i<j)
{
if(s[i]!=s[j])
{
break;
}
else
{
char x=s[i];
while(s[i]==x)
{
... | var minimumLength = function(s) {
const n = s.length;
let left = 0;
let right = n - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) break;
left++;
right--;
while (left <= right && s.charAt(left - 1) == s.charAt(left)) left++;
while (left <= ri... | Minimum Length of String After Deleting Similar Ends |
Given an integer n, return any array containing n unique integers such that they add up to 0.
Example 1:
Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
Example 2:
Input: n = 3
Output: [-1,0,1]
Example 3:
Input: n = 1
Output: [0]
Con... | class Solution:
def sumZero(self, n: int) -> List[int]:
q,p=divmod(n,2)
if p:
return list(range(-q, q+1))
else:
return list(range(-q,0))+list(range(1,q+1)) | class Solution {
public int[] sumZero(int n) {
int[] ans = new int[n];
int j=0;
for(int i=1;i<=n/2;i++)
{
ans[j] = i;
j++;
}
for(int i=1;i<=n/2;i++)
{
ans[j] = -i;
j++;
}
if(n%2!=0) ans[j... | class Solution {
public:
vector<int> sumZero(int n) {
if(n == 1){
return {0};
}else{
vector<int> res;
for(int i=n/2*-1;i<=n/2;i++){
if(i == 0){
if(n%2 == 0){
continue;
}else{
... | var sumZero = function(n) {
var num = Math.floor(n/2);
var res = [];
for(var i=1;i<=num;i++){
res.push(i,-i)
}
if(n%2!==0){
res.push(0)
}
return res
} | Find N Unique Integers Sum up to Zero |
You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices mu... | class UnionFind:
def __init__(self, n):
self.roots = [i for i in range(n)]
def find(self, v):
if self.roots[v] != v:
self.roots[v] = self.find(self.roots[v])
return self.roots[v]
def union(self, u, v):
self.roots[self.find(u)] = self.find(v)
class Solution:
... | class Solution {
public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) {
int minHamming = 0;
UnionFind uf = new UnionFind(source.length);
for (int [] swap : allowedSwaps) {
int firstIndex = swap[0];
int secondIndex = swap[1];
/... | class Solution {
public:
vector<int> parents;
vector<int> ranks;
int find(int a) {
if (a == parents[a])
return parents[a];
return parents[a] = find(parents[a]);
}
void uni(int a, int b) {
a = find(a);
b = find(b);
if (ranks[a] >= ranks[b]) {
... | var minimumHammingDistance = function(source, target, allowedSwaps) {
const n = source.length;
const uf = {};
const sizes = {};
const members = {};
// initial setup
for (let i = 0; i < n; i++) {
const srcNum = source[i];
uf[i] = i;
sizes[i] = 1;
... | Minimize Hamming Distance After Swap Operations |
Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
Example 1:
Input: nums = [2,2,3,4]
Output: 3
Explanation: Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
Example 2:
Inp... | class Solution {
public int triangleNumber(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
int count =0;
for(int k = n-1; k>=2; k--)
{
int i = 0;
int j = k-1;
while(i < j)
{
int sum = nums[i] +nums[j];
... | class Solution {
public int triangleNumber(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
int count =0;
for(int k = n-1; k>=2; k--)
{
int i = 0;
int j = k-1;
while(i < j)
{
int sum = nums[i] +nums[j];
... | class Solution {
public int triangleNumber(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
int count =0;
for(int k = n-1; k>=2; k--)
{
int i = 0;
int j = k-1;
while(i < j)
{
int sum = nums[i] +nums[j];
... | class Solution {
public int triangleNumber(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
int count =0;
for(int k = n-1; k>=2; k--)
{
int i = 0;
int j = k-1;
while(i < j)
{
int sum = nums[i] +nums[j];
... | Valid Triangle Number |
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) ... | class AuthenticationManager(object):
def __init__(self, timeToLive):
self.token = dict()
self.time = timeToLive # store timeToLive and create dictionary
def generate(self, tokenId, currentTime):
self.token[tokenId] = currentTime # store tokenId with currentTime
def renew(self, tok... | class AuthenticationManager {
private int ttl;
private Map<String, Integer> map;
public AuthenticationManager(int timeToLive) {
this.ttl = timeToLive;
this.map = new HashMap<>();
}
public void generate(String tokenId, int currentTime) {
map.put(tokenId, currentTime + th... | class AuthenticationManager {
int ttl;
unordered_map<string, int> tokens;
public:
AuthenticationManager(int timeToLive) {
ttl = timeToLive;
}
void generate(string tokenId, int currentTime) {
tokens[tokenId] = currentTime + ttl;
}
void renew(string tokenId, int currentTime) ... | // O(n)
var AuthenticationManager = function(timeToLive) {
this.ttl = timeToLive;
this.map = {};
};
AuthenticationManager.prototype.generate = function(tokenId, currentTime) {
this.map[tokenId] = currentTime + this.ttl;
};
AuthenticationManager.prototype.renew = function(tokenId, currentTime) {
let curr... | Design Authentication Manager |
You are given a 0-indexed array nums consisting of n positive integers.
The array nums is called alternating if:
nums[i - 2] == nums[i], where 2 <= i <= n - 1.
nums[i - 1] != nums[i], where 1 <= i <= n - 1.
In one operation, you can choose an index i and change nums[i] into any positive integer.
Ret... | class Solution:
def minimumOperations(self, nums: List[int]) -> int:
n = len(nums)
odd, even = defaultdict(int), defaultdict(int)
for i in range(n):
if i % 2 == 0:
even[nums[i]] += 1
else:
odd[nums[i]] += 1
topEven, secondEven =... | class Solution {
public int minimumOperations(int[] nums) {
int freq[][] = new int[100005][2];
int i, j, k, ans=0;
for(i = 0; i < nums.length; i++) {
freq[nums[i]][i&1]++;
}
for(i = 1, j=k=0; i <= 100000; i++) {
// Add the maximum frequency of odd indexes to maxi... | class Solution {
public:
int minimumOperations(vector<int>& nums) {
int totalEven = 0, totalOdd = 0;
unordered_map<int,int> mapEven, mapOdd;
for(int i=0;i<nums.size();i++) {
if(i%2==0) {
totalEven++;
mapEven[nums[i]]++;
}
... | /**
* @param {number[]} nums
* @return {number}
*/
var minimumOperations = function(nums) {
let countOddId = {}
let countEvenId = {}
if(nums.length === 1) return 0
if(nums.length === 2 && nums[0] === nums[1]) {
return 1
}
nums.forEach((n, i) => {
if(i%2) {
if(... | Minimum Operations to Make the Array Alternating |
Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] >... | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3:
return False
for i in range(1,len(arr)):
if arr[i] <= arr[i-1]:
if i==1:
return False
break
for j in range(i,len(arr)):
... | class Solution {
public boolean validMountainArray(int[] arr) {
// edge case
if(arr.length < 3) return false;
// keep 2 pointers
int i=0;
int j=arr.length-1;
// use i pointer to iterate through steep increase from LHS
while(i<j && arr[i]<arr[i+1]) {
... | class Solution {
public:
bool validMountainArray(vector<int>& arr) {
int flag = 1;
if((arr.size()<=2) || (arr[1] <= arr[0])) return false;
for(int i=1; i<arr.size(); i++){
if(flag){
if(arr[i] > arr[i-1]) continue;
i--;
flag = 0;
... | var validMountainArray = function(arr) {
let index = 0, length = arr.length;
//find the peak
while(index < length && arr[index] < arr[index + 1])index++
//edge cases
if(index === 0 || index === length - 1) return false;
//check if starting from peak to end of arr is descending order
while(index... | Valid Mountain Array |
You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: root = [0,0,null,0,0]
Output: 1
Explanation: One... | import itertools
# 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 minCameraHelper(self, root: Optional[TreeNode]) -> (int, int):
# Return 3 thing... | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* ... | class Solution {
public:
map<TreeNode*, int> mpr;
int dp[1009][3];
int minCameraCover(TreeNode* root)
{
int num = 0;
adres(root, num);
memset(dp, -1, sizeof(dp));
int t1 = dp_fun(root, 0), t2 = dp_fun(root, 1), t3 = dp_fun(root, 2);
return min({t1, t3});
}
... | var minCameraCover = function(root) {
let cam = 0;
// 0 --> No covered
// 1 --> covered by camera
// 2 --> has camera
function dfs(root) {
if(root === null) return 1;
const left = dfs(root.left);
const right = dfs(root.right);
if(left === 0 || right === 0) { // chil... | Binary Tree Cameras |
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).
The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.
For example, if s... | class Solution:
def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
x=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
a=""
for i in firstWord:
a=a+str(x.index(i))
b=""
f... | class Solution {
public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
int sumfirst=0, sumsecond=0, sumtarget=0;
for(char c : firstWord.toCharArray()){
sumfirst += c-'a';
sumfirst *= 10;
}
for(char c : secondWord.toCharArray()){
... | class Solution {
public:
bool isSumEqual(string firstWord, string secondWord, string targetWord) {
int first=0,second=0,target=0;
for(int i=0;i<firstWord.size();i++)
first=first*10 + (firstWord[i]-'a');
for(int i=0;i<secondWord.size();i++)
second=second*10 +(... | var isSumEqual = function(firstWord, secondWord, targetWord) {
let obj = {
'a' : '0',
"b" : '1',
"c" : '2',
"d" : '3',
"e" : '4',
'f' : '5',
'g' : '6',
'h' : '7',
'i' : '8',
"j" : '9'
}
let first = "", second = "", target = ""
... | Check if Word Equals Summation of Two Words |
You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names.
Return true if ... | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
from collections import defaultdict
g = defaultdict(list)
for e in equations:
if e[1] == '=':
x = e[0]
y = e[3]
g[x].append(y)
g[y].append(x)... | class Solution {
static int par[];
public static int findPar(int u) {
return par[u] == u ? u : (par[u] = findPar(par[u]));
}
public boolean equationsPossible(String[] equations) {
par = new int[26];
for (int i = 0; i < 26; i++) {
par[i] = i;
}
/*Fir... | class Solution {
public:
bool equationsPossible(vector<string>& equations) {
unordered_map<char,set<char>> equalGraph; //O(26*26)
unordered_map<char,set<char>> unEqualGraph; //O(26*26)
//build graph:
for(auto eq: equations){
char x = eq[0],... | /**
* @param {string[]} equations
* @return {boolean}
*/
class UnionSet {
constructor() {
this.father = new Array(26).fill(0).map((item, index) => index);
}
find(x) {
return this.father[x] = this.father[x] === x ? x : this.find(this.father[x]);
}
merge(a, b) {
const fa = t... | Satisfiability of Equality Equations |
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 1... | from collections import defaultdict
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
sign = "" if numerator*denominator >= 0 else "-"
numerator, denominator = abs(numerator), abs(denominator)
a = numerator//denominator
numerator %= denominator
... | class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if(numerator == 0){
return "0";
}
StringBuilder sb = new StringBuilder("");
if(numerator<0 && denominator>0 || numerator>0 && denominator<0){
sb.append("-");
}... | class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
unordered_map<int, int> umap;
string result = "";
if ((double) numerator / (double) denominator < 0) result.push_back('-');
long long l_numerator = numerator > 0 ? numerator : -(long long) numerator;
... | var fractionToDecimal = function(numerator, denominator) {
if(numerator == 0) return '0'
let result = ''
if(numerator*denominator <0){
result += '-'
}
let dividend = Math.abs(numerator)
let divisor = Math.abs(denominator)
result += Math.floor(dividend/divisor).toString()
... | Fraction to Recurring Decimal |
Given an integer n, return the number of trailing zeroes in n!.
Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.
Example 1:
Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: n = 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Example 3:
Input: n = 0
Output: 0
... | class Solution:
def trailingZeroes(self, n: int) -> int:
res = 0
for i in range(2, n+1):
while i > 0 and i%5 == 0:
i //= 5
res += 1
return res | class Solution {
public int trailingZeroes(int n) {
int count=0;
while(n>1) {count+=n/5; n=n/5;}
return count;
}
} | class Solution {
public:
int trailingZeroes(int n) {
int ni=0, mi=0;
for (int i=1; i<=n; i++){
int x=i;
while (x%2==0){
x= x>>1;
ni++;
}
while (x%5==0){
x= x/5;
mi++;
}
... | var trailingZeroes = function(n) {
let count=0
while(n>=5){
count += ~~(n/5)
n= ~~(n/5)
}
return count
}; | Factorial Trailing Zeroes |
You are given an integer array nums of length n.
Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:
F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
Return the maximum value of F(0), F(1), ..., F(n-1).
The test cases... | class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
preSum, cur = 0, 0
for i in range(len(nums)):
cur += i * nums[i]
preSum += nums[i]
ans = cur
for i in range(1, len(nums)):
cur -= len(nums) * nums[len(nums) - i]
cur +... | class Solution {
public int maxRotateFunction(int[] nums) {
int sum1 =0,sum2 = 0;
for(int i=0;i<nums.length;i++){
sum1 += nums[i];
sum2 += i*nums[i];
}
int result = sum2;
for(int i=0;i<nums.length;i++){
sum2 = sum2-sum1+(nums.length)*nums[i... | class Solution {
public:
int maxRotateFunction(vector<int>& A) {
long sum = 0, fn = 0;
int len = A.size();
for(int i=0;i<len;i++) {
sum += A[i];
fn += (i * A[i]);
}
long l = 1, r;
long newfn = fn;
while(l < len) {
... | var maxRotateFunction = function(nums) {
let n = nums.length;
let dp = 0;
let sum = 0;
for (let i=0; i<n;i++) {
sum += nums[i];
dp += i*nums[i];
}
let max = dp;
for (let i=1; i<n;i++) {
dp += sum - nums[n-i]*n;
max = Math.max(max, dp);
}
return... | Rotate Function |
Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
The following rules define a valid string:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '... | class Solution:
def checkValidString(self, s: str) -> bool:
left,right,star = deque(), deque(), deque() #indexes of all unmatched left right parens and all '*'
# O(n) where n=len(s)
for i,c in enumerate(s):
if c == '(': # we just append left paren's index
left.app... | class Solution{
public boolean checkValidString(String s){
Stack<Integer> stack = new Stack<>();
Stack<Integer> star = new Stack<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(' )
stack.push(i);
else if(s.charAt(i)=='*')
star.push(i);
else {
... | class Solution {
public:
bool checkValidString(string s) {
unordered_map<int, unordered_map<int, bool>> m;
return dfs(s, 0, 0, m);
}
// b: balanced number
bool dfs (string s, int index, int b, unordered_map<int, unordered_map<int, bool>>& m) {
if (index == s.length()) {
... | /**
* @param {string} s
* @return {boolean}
*/
var checkValidString = function(s) {
let map = {}
return check(s,0,0,map);
};
function check(s,index,open,map){
if(index == s.length){
return open == 0;
}
if(open < 0){
return false;
}
let string = index.toString() + "##" + ... | Valid Parenthesis String |
There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers numBottles and numExchange, return the maximum number of... | class Solution:
def numWaterBottles(self, a: int, b: int) -> int:
def sol(a,b,e,res):
if a!=0: res += a
if (a+e)<b: return res
a += e
new=a//b
e = a-(new*b)
a=new
return sol(a,b,e,res)
return sol(a... | class Solution {
public int numWaterBottles(int numBottles, int numExchange) {
int drinkedBottles = numBottles;
int emptyBottles = numBottles;
while(emptyBottles >= numExchange){
int gainedBottles = emptyBottles / numExchange;
drinkedBottles += gainedBottles;
... | class Solution {
public:
int numWaterBottles(int numBottles, int numExchange) {
int ex=0,remain=0,res=numBottles;
while(numBottles>=numExchange){
remain=numBottles%numExchange;
numBottles=numBottles/numExchange;
res+=numBottles;
numBottles+=remain;
... | var numWaterBottles = function(numBottles, numExchange) {
let count = 0;
let emptyBottles = 0;
while (numBottles > 0) {
count += numBottles;
emptyBottles += numBottles;
numBottles = Math.floor(emptyBottles / numExchange);
emptyBottles -= numBottles * numExchange;
}
... | Water Bottles |
Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
1 <= s.length <= 1000
s consists of lowercase Engl... | class Solution:
def smallestSubsequence(self, s: str) -> str:
# calculate the last occurence of each characters in s
last_occurence = {c: i for i, c in enumerate(s)}
stack = []
# check if element is in stack
instack = set()
for i, c in enumerate(s):
... | class Solution {
public String smallestSubsequence(String s) {
boolean[] inStack = new boolean [26];
int[] lastIdx = new int [26];
Arrays.fill(lastIdx,-1);
for(int i = 0; i < s.length(); i++){
lastIdx[s.charAt(i)-'a'] = i;
}
Deque<Character> dq = new Array... | class Solution {
public:
string smallestSubsequence(string s) {
string st="";
unordered_map< char ,int> m;
vector< bool> vis( 26,false);
for( int i=0;i<s.size();i++) m[s[i]]++;
stack< char> t;
t.push(s[0]) , m[s[0]]--;
st+=s[0];
... | var smallestSubsequence = function(s) {
let stack = [];
for(let i = 0; i < s.length; i++){
if(stack.includes(s[i])) continue;
while(stack[stack.length-1]>s[i] && s.substring(i).includes(stack[stack.length-1])) stack.pop();
stack.push(s[i]);
}
return stack.join("");
}; | Smallest Subsequence of Distinct Characters |
A positive integer is magical if it is divisible by either a or b.
Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: n = 1, a = 2, b = 3
Output: 2
Example 2:
Input: n = 4, a = 2, b = 3
Output: 6
Cons... | class Solution:
def nthMagicalNumber(self, N: int, A: int, B: int) -> int:
import math
lcm= A*B // math.gcd(A,B)
l,r=2,10**14
while l<=r:
mid=(l+r)//2
n = mid//A+mid//B-mid//lcm
if n>=N:
r=mid-1
else:
... | class Solution {
public int nthMagicalNumber(int n, int a, int b) {
long N=(long)n;
long A=(long)a;
long B=(long)b;
long mod=1000000007;
long min=Math.min(A,B);
long low=min;
long high=min*N;
long ans=0;
while(low<=high)
{
long mid=(high-low)/2+low;
long x=mid/A+m... | class Solution
{
public:
int lcm(int a, int b) // Finding the LCM of a and b
{
if(a==b)
return a;
if(a > b)
{
int count = 1;
while(true)
{
if((a*count)%b==0)
return a*count;
... | /**
* @param {number} n
* @param {number} a
* @param {number} b
* @return {number}
*/
var nthMagicalNumber = function(n, a, b) {
const gcd = (a1,b1)=>{
if(b1===0) return a1;
return gcd(b1,a1%b1)
}
const modulo = 1000000007;
let low = 0;
let high = 10e17;
let lcmAB = Math.flo... | Nth Magical Number |
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).
Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0... | class Solution:
def search(self, nums: List[int], target: int) -> bool:
nums.sort()
low=0
high=len(nums)-1
while low<=high:
mid=(low+high)//2
if nums[mid]==target:
return True
elif nums[mid]>target:
high=mid-1
... | class Solution {
public boolean search(int[] nums, int target) {
if (nums == null || nums.length == 0) return false;
int left = 0, right = nums.length-1;
int start = 0;
//1. find index of the smallest element
while(left < right) {
while (left < right && nums[left] == nums[left + 1])
... | class Solution {
public:
bool search(vector<int>& nums, int target) {
if( nums[0] == target or nums.back() == target ) return true;
// this line is redundant it reduces only the worst case when all elements are same to O(1)
const int n = nums.size();
int l = 0 , h ... | var search = function(nums, target) {
let found = nums.findIndex(c=> c==target);
if(found === -1) return false
else
return true
}; | Search in Rotated Sorted Array II |
You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi.
We can cu... | class Solution:
def videoStitching(self, clips: List[List[int]], T: int) -> int:
dp = [float('inf')] * (T + 1)
dp[0] = 0
for i in range(1, T + 1):
for start, end in clips:
if start <= i <= end:
dp[i] = min(dp[start] + 1, dp[i])
if dp[T]... | class Solution {
public int videoStitching(int[][] clips, int time) {
Arrays.sort(clips , (x , y) -> x[0] == y[0] ? y[1] - x[1] : x[0] - y[0]);
int n = clips.length;
int interval[] = new int[2];
int cuts = 0;
while(true){
cuts++;
int can_reach = 0;
... | class Solution {
public:
static bool comp(vector<int> a, vector<int> b){
if(a[0]<b[0]) return true;
else if(a[0]==b[0]) return a[1]>b[1];
return false;
}
int videoStitching(vector<vector<int>>& clips, int time) {
sort(clips.begin(), clips.end(), comp);
vector<vector<... | /** https://leetcode.com/problems/video-stitching/
* @param {number[][]} clips
* @param {number} time
* @return {number}
*/
var videoStitching = function(clips, time) {
// Memo
this.memo = new Map();
// Sort the clips for easier iteration
clips.sort((a, b) => a[0] - b[0]);
// If the output is `Infin... | Video Stitching |
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without... | class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
f = [0] + flowerbed + [0]
i, could_plant = 1, 0
while could_plant < n and i < len(f) - 1:
if f[i + 1]:
# 0 0 1 -> skip 3
i += 3
elif f[i]:
... | class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
if(flowerbed[0] != 1){
n--;
flowerbed[0] = 1;
}
for(int i = 1; i < flowerbed.length; i++){
if(flowerbed[i - 1] == 1 && flowerbed[i] == 1){
flowerbed[i - 1] = 0;
... | class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int count = 1;
int result = 0;
for(int i=0; i<flowerbed.size(); i++) {
if(flowerbed[i] == 0) {
count++;
}else {
result += (count-1)/2;
count = 0;
}
}
if(c... | /**
* @param {number[]} flowerbed
* @param {number} n
* @return {boolean}
*/
var canPlaceFlowers = function(flowerbed, n) {
for(let i=0 ; i<flowerbed.length ; i++) {
if((i===0 || flowerbed[i-1]===0) && flowerbed[i]===0 && (i===flowerbed.length-1 || flowerbed[i+1]===0)) {
flowerbed[i]=1;
... | Can Place Flowers |
You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.
You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (t... | class Solution:
def addRungs(self, rungs: List[int], dist: int) -> int:
rungs=[0]+rungs
i,ans=1,0
while i<len(rungs):
if rungs[i]-rungs[i-1] > dist:
ans+=ceil((rungs[i]-rungs[i-1])/dist)-1
i+=1
return ans
| class Solution {
public int addRungs(int[] rungs, int dist) {
int ans = 0;
for (int i=0 ; i<rungs.length ; i++) {
int d = (i==0) ? rungs[i] : rungs[i] - rungs[i-1];
if ( d > dist ) {
ans += d/dist;
ans += ( d%dist == 0 ) ? -1 : 0;
}... | class Solution {
public:
int addRungs(vector<int>& rungs, int dist)
{
//to keep the track of the number of extra rung to be added
long long int count = 0;
//our curr pos at the beggining
long long int currpos = 0;
//to keep the track of the next pos to be c... | var addRungs = function(rungs, dist) {
let res = 0;
let prev = 0;
for ( let i = 0; i < rungs.length; i++ ){
res += Math.floor(( rungs[i] - prev - 1 ) / dist );
prev = rungs[i];
}
return res;
}; | Add Minimum Number of Rungs |
There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop t... | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
endheap = []
startheap = []
for i in range(len(trips)):
endheap.append((trips[i][2],trips[i][0],trips[i][1]))
startheap.append((trips[i][1],trips[i][0],trips[i][2]))
... | class Solution {
public boolean carPooling(int[][] trips, int capacity) {
Map<Integer, Integer> destinationToPassengers = new TreeMap<>();
for(int[] trip : trips) {
int currPassengersAtPickup = destinationToPassengers.getOrDefault(trip[1], 0);
int currPassengersAtDrop = desti... | class Solution {
typedef pair<int, int> pd;
public:
bool carPooling(vector<vector<int>>& trips, int capacity) {
int seat=0;
priority_queue<pd, vector<pd>, greater<pd>>pq;
for(auto it : trips)
{
pq.push({it[1], +it[0]});
pq.push({it[2], -it[0]});
}
... | /**
* @param {number[][]} trips
* @param {number} capacity
* @return {boolean}
*/
var carPooling = function(trips, capacity) {
// sort trips by destination distance
trips.sort((a, b) => a[2] - b[2]);
// build result array, using max distance
const lastTrip = trips[trips.length - 1];
co... | Car Pooling |
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Exampl... | class Solution:
def reverse(self,arr,left,right):
while left < right:
arr[left],arr[right] = arr[right], arr[left]
left, right = left + 1, right - 1
return arr
def rotate(self, nums: List[int], k: int) -> None:
length = len(nums)
k = k % length
l, ... | class Solution {
public void rotate(int[] nums, int k) {
reverse(nums , 0 , nums.length-1);
reverse(nums , 0 , k-1);
reverse(nums , k , nums.length -1);
}
public static void reverse(int[] arr , int start , int end){
while(start<end){
int temp = arr[start];
... | class Solution {
public:
void rotate(vector<int>& nums, int k) {
vector<int> temp(nums.size());
for(int i = 0; i < nums.size() ;i++){
temp[(i+k)%nums.size()] = nums[i];
}
nums = temp;
}
}; | /**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
const len = nums.length;
k %= len;
const t = nums.splice(len - k, k);
nums.unshift(...t);
}; | Rotate Array |
You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.
We want to reformat the string s such that each group contains exactly k characters, except for the first group, which ... | class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
new_str = s.replace("-", "")
res = ""
j = len(new_str)-1
i = 0
while j >= 0:
res += new_str[j].upper()
i += 1
if i == k and j != 0:
res += "-"
... | class Solution {
public String licenseKeyFormatting(String s, int k) {
StringBuilder answer = new StringBuilder();
int length = 0;
// Iterate Backwards to fullfill first group condition
for(int i=s.length()-1;i>=0;i--) {
if(s.charAt(i) == '-') {
continue;
... | class Solution {
public:
string licenseKeyFormatting(string s, int k) {
stack<char>st;
string ans="";
for(int i=0;i<s.length();i++){
if(isalpha(s[i]) || isdigit(s[i])){
st.push(s[i]);
}
}
int i=0;
while(st.size()>0){
... | // Please upvote if you like the solution. Thanks
var licenseKeyFormatting = function(s, k) {
let str=s.replace(/[^A-Za-z0-9]/g,"").toUpperCase()
let ans=""
let i=str.length;
while(i>0){
ans="-"+str.substring(i-k,i)+ans // we are taking k characters from the end of string and adding it to answer
... | License Key Formatting |
You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i].
You are further given two integers l... | class Solution:
def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:
l = [0]
for i in differences:
l.append(l[-1]+i)
return max(0,(upper-lower+1)-(max(l)-min(l))) | class Solution {
public int numberOfArrays(int[] differences, int lower, int upper) {
ArrayList<Integer> ans = new ArrayList<>();
ans.add(lower);
int mn = lower;
int mx = lower;
for (int i = 0; i < differences.length; i++) {
int d = differences[i];
... | using ll = long long int;
class Solution {
public:
int numberOfArrays(vector<int>& differences, int lower, int upper) {
vector<ll> ans;
ans.push_back(lower);
ll mn = lower;
ll mx = lower;
for (const auto& d: differences) {
ans.push_back(d + ans.back());
... | var numberOfArrays = function(differences, lower, upper) {
let temp = 0;
let res = 0;
let n = lower;
for (let i = 0; i < differences.length; i++) {
temp += differences[i];
differences[i] = temp;
}
const min = Math.min(...differences);
const max = Math.max(...differences);
... | Count the Hidden Sequences |
You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright:
numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - ... | class Solution:
def maxScoreIndices(self, nums: List[int]) -> List[int]:
zeroFromLeft = [0] * (len(nums) + 1)
oneFromRight = [0] * (len(nums) + 1)
for i in range(len(nums)):
if nums[i] == 0:
zeroFromLeft[i + 1] = zeroFromLeft[i] + 1
else:
... | class Solution {
public List<Integer> maxScoreIndices(int[] nums) {
int N = nums.length;
List<Integer> res = new ArrayList<>();
int[] pref = new int[N + 1];
pref[0] = 0; // at zeroth division we have no elements
for(int i = 0; i < N; ++i) pref[i+1] = nums[i] + pref[i];
... | class Solution {
public:
vector<int> maxScoreIndices(vector<int>& nums) {
int n=nums.size();
if(n==1)
{
if(nums[0]==0)
return {1};
else
return {0};
}
int one=0,zero=0;
for(int i=0;i<n;i++)
{
i... | /**
* @param {number[]} nums
* @return {number[]}
*/
var maxScoreIndices = function(nums) {
let n=nums.length;
// initialize 3 arrays for counting with n+1 size
let zeros = new Array(n+1).fill(0);
let ones = new Array(n+1).fill(0);
let total = new Array(n+1).fill(0);
/... | All Divisions With the Highest Score of a Binary Array |
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from heapq import heappush,heappop
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
heap = []
heapq.heap... | class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length < 1) return null;
//add the first chunk of linkedlist to res,
//so later we started from index 1
ListNode res = lists[0];
//traverse the lists and start merge by calling mergeTwo
for(int i = 1; ... | class Solution {
public:
struct compare
{
bool operator()(ListNode* &a,ListNode* &b)
{
return a->val>b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*,vector<ListNode*>,compare>minh;
for(int i=0;i<lists.size();i++)... | var mergeKLists = function(lists) {
// Use min heap to keep track of the smallest node in constant time.
// Enqueue and dequeue will be log(k) where k is the # of lists
// b/c we only need to keep track of the next node for each list
// at any given time.
const minHeap = new MinPriorityQueue({ p... | Merge k Sorted Lists |
You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.
For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].
Return the minimum number of operations to make an... | class Solution:
def minimumReplacement(self, nums) -> int:
ans = 0
n = len(nums)
curr = nums[-1]
for i in range(n - 2, -1, -1):
if nums[i] > curr:
q = nums[i] // curr
if nums[i] == curr * q:
nums[i] = curr
... | class Solution {
public long minimumReplacement(int[] nums) {
long ret = 0L;
int n = nums.length;
int last = nums[n - 1];
for(int i = n - 2;i >= 0; i--){
if(nums[i] <= last){
last = nums[i];
continue;
}
if(nums[i] % ... | class Solution {
public:
long long minimumReplacement(vector<int>& nums) {
long long res=0;
int n=nums.size();
int mxm=nums[n-1];
long long val;
for(int i=n-2;i>=0;i--)
{
// minimum no. of elemetns nums[i] is divided such that every number is less than mxm... | /**
* @param {number[]} nums
* @return {number}
*/
var minimumReplacement = function(nums) {
const n = nums.length;
let ans = 0;
for(let i = n - 2 ; i >= 0 ; i--){
if(nums[i]>nums[i+1]){
const temp = Math.ceil(nums[i]/nums[i+1]);
ans += temp - 1;
nums[i] = Math... | Minimum Replacements to Sort the Array |
Given two integers num and k, consider a set of positive integers with the following properties:
The units digit of each integer is k.
The sum of the integers is num.
Return the minimum possible size of such a set, or -1 if no such set exists.
Note:
The set can contain multiple instances of the same integer, ... | class Solution:
def minimumNumbers(self, num: int, k: int) -> int:
if num == 0:
return 0
if k == 0:
return 1 if num % 10 == 0 else -1
for n in range(1, min(num // k, 10) + 1):
if (num - n * k) % 10 == 0:
return n
... | class Solution
{
public int minimumNumbers(int num, int k)
{
if(num == 0)
return 0;
if(k == 0)
if(num % 10 == 0) //E.g. 20,1590,3000
return 1;
else
return -1;
for(int i = 1; i <= num/k; i++) // Start with set size 1 and ... | class Solution {
public:
//same code as that of coin change
int coinChange(vector<int>& coins, int amount) {
int Max = amount + 1;
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int i = 0; i <= amount; i++) {
for (int j = 0; j < coins.size(); j++) {
... | var minimumNumbers = function(num, k) {
if (num === 0) return 0;
for (let i = 1; i <= 10; i++) {
if (k*i % 10 === num % 10 && k*i <= num) return i;
if (k*i > num) return -1
} return -1;
}; | Sum of Numbers With Units Digit K |
You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n).
In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the ele... | class Solution:
def minOperations(self, n: int) -> int:
return sum([n-x for x in range(n) if x % 2 != 0]) | class Solution {
public int minOperations(int n) {
int ans = (n/2)*(n/2);
if(n%2==1){
ans += n/2;
}
return ans;
}
} | class Solution {
public:
int minOperations(int n) {
int s=0;
for(int i=0; i<= (n-1)/2; ++i){
s += fabs(n-(2*i+1));
}
return s;
}
}; | var minOperations = function(n) {
let reqNum;
if(n%2!=0){
reqNum = Math.floor(n/2)*2+1
}else{
reqNum = ((Math.floor(n/2))*2+1 + (Math.floor(n/2) -1)*2+1)/2
}
let count = 0;
for(let i=1; i<reqNum; i +=2){
count += (reqNum-i)
}
return count
}; | Minimum Operations to Make Array Equal |
You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums.
You then do the following steps:
If original is found in nums, multiply it by two (i.e., set original = 2 * original).
Otherwise, stop the process.
Repeat this process w... | class Solution:
def findFinalValue(self, nums: List[int], original: int) -> int:
while original in nums:
original *= 2
return original | class Solution
{
public int findFinalValue(int[] nums, int original)
{
HashSet<Integer> set = new HashSet<>();
for(int i : nums)
if(i >= original)
set.add(i);
while(true)
if(set.contains(original))
original *= 2;
else
... | class Solution {
public:
int findFinalValue(vector<int>& nums, int original) {
int n = 1;
for(int i = 0; i<n;++i)
{
if(find(nums.begin(),nums.end(),original) != nums.end()) //find func detailled explanation above
{
original *= 2;
n +... | var findFinalValue = function(nums, original) {
while (nums.includes(original)) {
original = original * 2
}
return original
}; | Keep Multiplying Found Values by Two |
A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
For example, for arr = [1,2,3], the following are considered permutations of arr: [1,2,3], [1,3,2], [3,1,2], [2,3,1].
The next permutation of an array of integers is the next lexicographically greater permutatio... | class Solution:
def nextPermutation(self, nums) -> None:
firstDecreasingElement = -1
toSwapWith = -1
lastIndex = len(nums) - 1
# Looking for an element that is less than its follower
for i in range(lastIndex, 0, -1):
if nums[i] > nums[i - 1]:
firs... | class Solution {
public void nextPermutation(int[] nums) {
// FIND peek+1
int nextOfPeak = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
nextOfPeak = i - 1;
break;
}
}
// Return reverse Ar... | class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size()==1)
return;
int i=nums.size()-2;
while(i>=0 && nums[i]>=nums[i+1]) i--;
if(i>=0){
int j=nums.size()-1;
while(nums[i] >= nums[j]) j--;
swap(nums[j], nums[... | /**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
const dsc = nums.slice();
dsc.sort((a, b) => b - a);
if (dsc.every((n, i) => n === nums[i])) {
nums.sort((a, b) => a - b);
} else {
const len =... | Next Permutation |
There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.
Given the five integers m, n, maxMove... | class Solution:
def helper(self, m, n, maxMove, startRow, startColumn, mat,dp) -> int:
if startRow < 0 or startRow >=m or startColumn < 0 or startColumn >=n:
return 1
if dp[maxMove][startRow][startColumn]!=-1:
return dp[maxMove][startRow][startColumn]
... | class Solution {
int[][][] dp;
int mod = 1000000007;
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
dp = new int[m][n][maxMove + 1];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k <= maxMove; k++)
... | vector<vector<vector<int>>> dp;
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
int mod = 1e9+7;
int fun(int i,int j,int n,int m,int k){
if(i < 0 || j < 0 || i == n || j == m)return 1;
else if(k == 0)return 0;
if(dp[i][j][k] != -1)return dp[i][j][k];
int ans = 0;
for(int c = 0; c <... | vector<vector<vector<int>>> dp;
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
int mod = 1e9+7;
int fun(int i,int j,int n,int m,int k){
if(i < 0 || j < 0 || i == n || j == m)return 1;
else if(k == 0)return 0;
if(dp[i][j][k] != -1)return dp[i][j][k];
int ans = 0;
for(int c = 0; c <... | Out of Boundary Paths |
Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.
Example 1:
Input: nums = [-2,5,-1], lower = -2, upper = 2
Outp... | class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
acc = list(accumulate(nums))
ans = a = 0
for n in nums:
a += n
ans += sum(1 for x in acc if lower <= x <= upper)
acc.pop(0)
lower += n
upper +=... | class Solution {
public int countRangeSum(int[] nums, int lower, int upper) {
int n = nums.length, ans = 0;
long[] pre = new long[n+1];
for (int i = 0; i < n; i++){
pre[i+1] = nums[i] + pre[i];
}
Arrays.sort(pre);
int[] bit = new int[pre.length+2];
... | class Solution {
public:
using ll = long long;
int countRangeSum(vector<int>& nums, int lower, int upper) {
// Build prefix sums
vector<ll> prefixSums(nums.size() + 1, 0);
for (int i = 0; i < nums.size(); i++) {
prefixSums[i + 1] = prefixSums[i] + nums[i];
}
... | var countRangeSum = function(nums, lower, upper) {
let preSum = Array(nums.length + 1).fill(0);
let count = 0;
// create preSum array, use preSum to check the sum range
for (let i = 0; i < nums.length; i++) {
preSum[i + 1] = preSum[i] + nums[i];
}
const sort = function(preSum) {
if (preSum.len... | Count of Range Sum |
Given the root of a binary tree, calculate the vertical order traversal of the binary tree.
For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).
The vertical order traversal of a binary tree is... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def verticalTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solutio... | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) ... | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var verticalTraversal = funct... | Vertical Order Traversal of a Binary Tree |
You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].
For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).
Return an array answer where answer[i] is the answer to the ith... | class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
"""
arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
find pref xor of arr
pref = [x,x,x,x]
for each query find the left and right indices
the xor for range (l, r) would be... | class Solution
{
public int[] xorQueries(int[] arr, int[][] queries)
{
int[] ans = new int[queries.length];
int[] xor = new int[arr.length];
xor[0] = arr[0];
// computing prefix XOR of arr
for(int i = 1; i < arr.length; i++)
{
xor[i] = arr[i] ^ xor[i-1... | class Solution {
public:
// we know that (x ^ x) = 0,
// arr = [1,4,8,3,7,8], let we have to calculate xor of subarray[2,4]
// (1 ^ 4 ^ 8 ^ 3 ^ 7) ^ (1 ^ 4) = (8 ^ 3 ^ 7), this is nothing but prefix[right] ^ prefix[left - 1]
// (1 ^ 1 = 0) and (4 ^ 4) = 0
vector<int> ... | var xorQueries = function(arr, queries) {
let n = arr.length;
while ((n & (n - 1)) != 0) {
n++;
}
const len = n;
const tree = new Array(len * 2).fill(0);
build(tree, 1, 0, len - 1);
const res = [];
for (let i = 0; i < queries.length; i++) {
const [s... | XOR Queries of a Subarray |
You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.
A guard can see every cell in the four cardinal directions (no... | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
dp = [[0] * n for _ in range(m)]
for x, y in guards+walls:
dp[x][y] = 1
directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]
for x, y in g... | class Solution
{
public int countUnguarded(int m, int n, int[][] guards, int[][] walls)
{
int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
char[][] grid= new char[m][n];
int count = m*n - guards.length - walls.length;
for(int[] wall : walls)
{
int x = wall[0], y = ... | class Solution {
public:
void dfs( vector<vector<int>> &grid,int x,int y,int m,int n,int dir){
if(x<0 || y<0 || x>=m || y>=n) return;
if(grid[x][y]==2 || grid[x][y]==1) return;
grid[x][y]=3;
if(dir==1){
dfs(grid,x+1,y,m,n,dir);
}
else if(dir==2){
... | var countUnguarded = function(m, n, guards, walls) {
let board = new Array(m).fill(0).map(_=>new Array(n).fill(0))
// 0 - Empty
// 1 - Guard
// 2 - Wall
// 3 - Guard view
const DIRECTIONS = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1]
]
for(let [guard... | Count Unguarded Cells in the Grid |
You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A': Absent.
'L': Late.
'P': Present.
The student is eligible for an attendance award if t... | class Solution:
def checkRecord(self, s: str) -> bool:
eligible = True
for i in range(0, len(s)-2):
if s[i:i+3] == "LLL":
eligible = False
absent = 0
for i in range(len(s)):
if s[i] == "A":
absent +=1
if absent>=2:
... | class Solution {
public boolean checkRecord(String s) {
int size=s.length();
if(s.replace("A","").length()<=size-2||s.indexOf("LLL")!=-1)return false;
return true;
}
} | class Solution {
public:
bool checkRecord(string s);
};
/*********************************************************/
bool Solution::checkRecord(string s) {
int i, size = s.size(), maxL=0, countA=0, countL=0;
for (i = 0; i < size; ++i) {
if (s[i] == 'L') {
++countL;
} else {
... | var checkRecord = function(s) {
let absent = 0;
let lates = 0;
for (let i = 0; i < s.length; i++) {
if(s[i] === 'L') {
lates++;
if(lates > 2) return false;
} else {
lates = 0;
if(s[i] === 'A') {
absent++;
if(abse... | Student Attendance Record I |
You are given two strings s and t of the same length and an integer maxCost.
You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).
Return the maximum length of a substring of s that can be change... | class Solution(object):
def equalSubstring(self, s, t, maxCost):
"""
:type s: str
:type t: str
:type maxCost: int
:rtype: int
"""
best = 0
windowCost = 0
l = 0
for r in range(len(s)):
... | class Solution {
public int equalSubstring(String s, String t, int maxCost) {
int ans =0;
int tempcost =0;
int l =0 ;
int r= 0 ;
for(;r!=s.length();r++){
tempcost += Math.abs(s.charAt(r)-t.charAt(r));
while(tempcost>maxCost){
tempcost -... | class Solution {
public:
int equalSubstring(string s, string t, int maxCost) {
int l = 0, r = 0, currCost = 0, n = s.length(), maxLen = 0;
while(r < n) {
currCost += abs(s[r] - t[r]);
r++;
while(currCost > maxCost) {
currCost -= abs(s[l] - t[l]);... | var equalSubstring = function(s, t, maxCost) {
let dp = [], ans = 0;
for (let i = 0, j = 0, k = 0; i < s.length; i++) {
// overlay
k += dp[i] = abs(s[i], t[i]);
// non first
if (k > maxCost) {
k -= dp[j], j++;
continue;
}
... | Get Equal Substrings Within Budget |
For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0.
Given strings sequence and word,... | class Solution:
def maxRepeating(self, sequence: str, word: str) -> int:
if word not in sequence:
return 0
left = 1
right = len(sequence) // len(word)
while left <= right:
mid = (left + right) // 2
if word * mid in sequence:
left =... | class Solution {
public int maxRepeating(String s, String w) {
if(w.length()>s.length()) return 0;
int ans=0;
StringBuilder sb=new StringBuilder("");
while(sb.length()<=s.length()){
sb.append(w);
if(s.contains(sb)) ans++;
else break;
}
... | class Solution {
public:
int maxRepeating(string sequence, string word) {
int k = 0;
string temp = word;
while(sequence.find(temp) != string::npos){
temp += word;
k++;
}
return k;
}
}; | var maxRepeating = function(sequence, word) {
let result = 0;
while (sequence.includes(word.repeat(result + 1))) {
result += 1;
};
return result;
}; | Maximum Repeating Substring |
A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.
Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Example 1:
Input: n = 5
Output: 2
Explanation: The square triples are (3,4,5) and (4,3,5).
Example 2:
Input: n = 10
Output: 4
Expla... | class Solution:
def countTriples(self, n: int) -> int:
c = 0
for i in range(1, n+1):
for j in range(i+1, n+1):
sq = i*i + j*j
r = int(sq ** 0.5)
if ( r*r == sq and r <= n ):
c +=2
return c | class Solution {
public int countTriples(int n) {
int c = 0;
for(int i=1 ; i<=n ; i++){
for(int j=i+1 ; j<=n ; j++){
int sq = ( i * i) + ( j * j);
int r = (int) Math.sqrt(sq);
if( r*r == sq && r <= n )
c += 2;
... | class Solution {
public:
int countTriples(int n) {
int res = 0;
for (int a = 3, sqa; a < n; a++) {
sqa = a * a;
for (int b = 3, sqc, c; b < n; b++) {
sqc = sqa + b * b;
c = sqrt(sqc);
if (c > n) break;
res += c *... | var countTriples = function(n) {
let count = 0;
for (let i=1; i < n; i++) {
for (let j=1; j < n; j++) {
let root = Math.sqrt(j*j + i*i)
if (Number.isInteger(root) && root <= n) {
count++
}
}
}
return count
}; | Count Square Sum Triples |
You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:
horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and
verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertic... | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
mxHr = 0
prev = 0
for i in horizontalCuts:
mxHr = max(mxHr, i-prev)
prev = i
mxHr =... | import java.math.BigInteger;
class Solution {
public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
Arrays.sort(horizontalCuts);
Arrays.sort(verticalCuts);
int i;
int hMax=horizontalCuts[0];
for(i=1;i<horizontalCuts.length;i++)
// if(hMax < ... | class Solution {
public:
int maxArea(int h, int w, vector<int>& horizontalCuts, vector<int>& verticalCuts) {
int mod = 1e9 + 7;
sort(horizontalCuts.begin(), horizontalCuts.end());
sort(verticalCuts.begin(), verticalCuts.end());
// cout << 1;
horizontalCuts.push_back(h);
... | var maxArea = function(h, w, horizontalCuts, verticalCuts) {
horizontalCuts.sort((a,b) => a-b)
verticalCuts.sort((a,b) => a-b)
let max_hor_dis = Math.max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.length-1])
let max_ver_dis = Math.max(verticalCuts[0], w - verticalCuts[verticalCuts.length-1])
... | Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts |
Sometimes people repeat letters to represent extra feeling. For example:
"hello" -> "heeellooo"
"hi" -> "hiiii"
In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".
You are given a string s and an array of query strings words. A query word is... | class Solution:
def expressiveWords(self, s: str, words: List[str]) -> int:
# edge cases
if len(s) == 0 and len(words) != 0:
return False
if len(words) == 0 and len(s) != 0:
return False
if len(s) == 0 and len(words) == 0:
return True
... | class Solution {
private String getFreqString(String s) {
int len = s.length();
StringBuilder freqString = new StringBuilder();
int currFreq = 1;
char prevChar = s.charAt(0);
freqString.append(s.charAt(0));
for(int i = 1; i<len; i++) {
if(s.charAt(i) == pr... | class Solution {
public:
// Basically get the length of a repeated sequence starting at pointer p.
int getRepeatedLen(string& s, int p) {
int res = 0;
char c = s[p];
while(p < s.size() && s[p] == c) {
res++;
p++;
}
return res;
}
... | /**
* @param {string} s
* @param {string[]} words
* @return {number}
*/
var expressiveWords = function(s, words) {
let arr = [];
let curr = 0
while(curr < s.length){
let count = 1
while(s[curr] === s[curr+1]){
count++;
curr++
}
arr.push([s[curr] , ... | Expressive Words |
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input:... | class Solution:
def maxSubArray(self, nums: List[int]) -> int:
def kadane(i):
if F[i] != None:
return F[i]
F[i] = max(nums[i],kadane(i-1) + nums[i])
return F[i]
n = len(nums)
F = [None for _ in range(n)]
F[0] = nums[0]
kadan... | class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length;
int currmax = 0;
int gmax = nums[0];
for(int i=0;i<n;i++) {
currmax+=nums[i];
gmax=Math.max(gmax, currmax);
currmax=Math.max(currmax, 0);
}
return gmax;
... | class Solution {
public:
int maxSubArray(vector<int>& nums)
{
int m = INT_MIN, sm = 0;
for (int i = 0; i < nums.size(); ++i)
{
sm += nums[i];
m = max(sm, m);
if (sm < 0) sm = 0;
}
return m;
}
}; | /**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let max = Number.MIN_SAFE_INTEGER;
let curr = 0;
for (let i = 0; i < nums.length; i++) {
if (curr < 0 && nums[i] > curr) {
curr = 0;
}
curr += nums[i];
max = Math.max(max, curr);
}
retur... | Maximum Subarray |
Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:
1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
2 which means go to the cell to the left. (i.e go from grid[i][j] t... | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
changes = [[float("inf") for _ in range(len(grid[0]))] for _ in range(len(grid))]
heap = [(0,0,0)]
dirn = [(0,1),(0,-1),(1,0),(-1,0)]
while heap:
dist,r,c = heapq.heappop(heap)
if r >= len(grid) ... | class Solution {
int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};
private boolean isValid(int i,int j,int n,int m) {
return i<n && j<m && i>=0 && j>=0;
}
private boolean isValidDirection(int [][]grid,int []currEle,int nx,int ny) {
int nextX=currEle[0],nextY = currEle[1];
int n =gri... | #define vv vector<int>
class Solution {
public:
int dx[4]={0 , 0, 1 , -1};
int dy[4]={1 , -1 , 0 , 0};
int minCost(vector<vector<int>>& grid) {
int m=grid.size();
int n=grid[0].size();
priority_queue< vv , vector<vv> , greater<vv>> pq;
vector<vector<int>> dp(m+3 , vecto... | const minCost = function (grid) {
const m = grid.length,
n = grid[0].length,
checkPos = (i, j) =>
i > -1 && j > -1 && i < m && j < n && !visited[i + "," + j],
dir = { 1: [0, 1], 2: [0, -1], 3: [1, 0], 4: [-1, 0] },
dfs = (i, j) => {
if (!checkPos(i, j)) return false;
if (i === m - 1 && j === n - 1) re... | Minimum Cost to Make at Least One Valid Path in a Grid |
Alice and Bob take turns playing a game, with Alice starting first.
You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:
Choose an index i where num[i] == '?'.
Replace num[i] with any digit be... | class Solution:
def sumGame(self, num: str) -> bool:
n = len(num)
q_cnt_1 = s1 = 0
for i in range(n//2): # get digit sum and question mark count for the first half of `num`
if num[i] == '?':
q_cnt_1 += 1
else:
s1 += int(num[i])
... | class Solution {
public boolean sumGame(String num) {
int q = 0, d = 0, n = num.length();
for (int i = 0; i < n; i++){
if (num.charAt(i) == '?'){
q += 2* i < n? 1 : -1;
}else{
d += (2 * i < n? 1 : -1) * (num.charAt(i) - '0');
}
... | class Solution {
public:
bool sumGame(string num) {
const int N = num.length();
int lDigitSum = 0;
int lQCount = 0;
int rDigitSum = 0;
int rQCount = 0;
for(int i = 0; i < N; ++i){
if(isdigit(num[i])){
if(i < N / 2){
... | /**
* @param {string} num
* @return {boolean}
*/
var sumGame = function(num) {
function getInfo(s) {
var sum = 0;
var ques = 0;
for(let c of s.split(''))
if (c !== '?') sum += c - 0;
else ques++;
return [sum, ques];
}
function check(sum1, ... | Sum Game |
You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:
i < j < k,
nums[j] - nums[i] == diff, and
nums[k] - nums[j] == diff.
Return the number of unique arithmetic triplets.
Exam... | class Solution:
def arithmeticTriplets(self, nums: List[int], diff: int) -> int:
ans = 0
n = len(nums)
for i in range(n):
if nums[i] + diff in nums and nums[i] + 2 * diff in nums:
ans += 1
return ans | class Solution {
public int arithmeticTriplets(int[] nums, int diff) {
int result = 0;
int[] map = new int[201];
for(int num: nums) {
map[num] = 1;
if(num - diff >= 0) {
map[num] += map[num - diff];
}
if(map[num] >= 3) result... | class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
int ans=0;
for(int i=0;i<nums.size();i++){
for(int j=i+1;j<nums.size();j++){
for(int k=j+1;k<nums.size();k++){
if((nums[j]-nums[i])==diff && (nums[k]-nums[j])==diff){
... | /**
* @param {number[]} nums
* @param {number} diff
* @return {number}
*/
var arithmeticTriplets = function(nums, diff) {
count = 0
for(let i = 0; i < nums.length - 2; i++){
for(let j = i + 1; j < nums.length - 1; j++){
for(let k = j + 1; k < nums.length; k++){
if(i < j && j < ... | Number of Arithmetic Triplets |
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = ... | class Solution:
def letterCombinations(self, digits: str) -> List[str]:
mapping = {"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
... | class Solution {
String[] num = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
List<String> ll = new ArrayList<>();
StringBuilder sb = new StringBuilder();
if (digits.length() != 0) {
combination(dig... | class Solution {
public:
void solve(string digit,string output,int index,vector<string>&ans,string mapping[])
{ // base condition
if(index>=digit.length())
{
ans.push_back(output);
return;
}
// digit[index] gives character value to change in integer subtr... | var letterCombinations = function(digits) {
if(!digits) return []
let res = []
const alpha = {
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs",
8: "tuv",
9: "wxyz"
}
const dfs = (i, digits, temp)=>{
if(i === digits.length){
res.push(temp.join(''))
... | Letter Combinations of a Phone Number |
Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n point... | class Solution:
def numberOfSets(self, n: int, k: int) -> int:
MOD = 10**9 + 7
@lru_cache(None)
def dp(i, k, isStart):
if k == 0: return 1 # Found a way to draw k valid segments
if i == n: return 0 # Reach end of points
ans = dp(i+1, k, isStart) # Skip ith... | class Solution {
Integer[][][] memo;
int n;
public int numberOfSets(int n, int k) {
this.n = n;
this.memo = new Integer[n+1][k+1][2];
return dp(0, k, 1);
}
int dp(int i, int k, int isStart) {
if (memo[i][k][isStart] != null) return memo[i][k][isStart];
if (k =... | class Solution {
public:
int MOD = 1e9+7;
int sumDyp(int n, int k, vector<vector<int>> &dp, vector<vector<int>> &sumDp)
{
if(n < 2)
return 0;
if(sumDp[n][k] != -1)
return sumDp[n][k];
sumDp[n][k] = ((sumDyp(n-1, k, dp, sumDp)%MOD) + (dyp(n, k... | var numberOfSets = function(n, k) {
return combinations(n+k-1,2*k)%(1e9+7)
};
var combinations=(n,k)=>{
var dp=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>1))
for (let i = 1; i <=n; i++)
for (let k = 1; k <i; k++)
dp[i][k]=(dp[i-1][k-1]+dp[i-1][k]) %(1e9+7)
return dp[n][k]
} | Number of Sets of K Non-Overlapping Line Segments |
Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
Ret... | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
column = ['Table']
dish = []
table_dict = {}
for order_row in orders :
if order_row[-1] not in dish :
dish.append(order_row[-1])
for order_row in orders :... | class Solution {
public List<List<String>> displayTable(List<List<String>> orders) {
List<List<String>> ans = new ArrayList<>();
List<String> head = new ArrayList<>();
head.add("Table");
Map<Integer, Map<String,Integer>> map = new TreeMap<>();
for(List<String> s: orders){
... | class Solution {
public:
vector<vector<string>> displayTable(vector<vector<string>>& orders) {
vector<vector<string>>ans;
map<int,map<string,int>>m;
set<string>s; //Sets are useful as they dont contain duplicates as well arranges the strings in order.
for(auto row:orders)
{
s.i... | var displayTable = function(orders) {
var mapOrders = {};
var tables = [];
var dishes = [];
for(var i=0;i<orders.length;i++){
//if entry of table doesn't exist in mapOrders
if(mapOrders[orders[i][1]] == undefined){
//conver table number to integer
var tableNo = Nu... | Display Table of Food Orders in a Restaurant |
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.
The grammar can best be understood through simple examples:
Single letters represent a singleton set containing that word.
R("a") = {"a"}
R("w") = {"w"}
... | class Solution:
def braceExpansionII(self, expression: str) -> List[str]:
s = list(reversed("{" + expression + "}"))
def full_word():
cur = []
while s and s[-1].isalpha():
cur.append(s.pop())
return "".join(cur)
... | class Solution {
// To Get the value of index traversed in a recursive call.
int index = 0;
public List<String> braceExpansionII(String expression) {
List<String> result = util(0, expression);
Set<String> set = new TreeSet<>();
set.addAll(result);
return new ArrayList<>(set)... | class Solution {
public:
vector<string> braceExpansionII(string expression) {
string ss;
int n = expression.size();
for(int i = 0; i < n; i++){
if(expression[i] == ','){
ss += '+';
}
else{
ss += expression[i];
... | var braceExpansionII = function(expression) { // , mutiplier = ['']
const char = ('{' + expression + '}').split('').values()
const result = [...rc(char)];
result.sort((a,b) => a.localeCompare(b));
return result;
};
function rc (char) {
const result = new Set();
let resolved = ['']
le... | Brace Expansion II |
Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position.
For example, if s = "abcde", then it will be "bcdea" after one shift.
Example 1:
Input: s = "abcde", goal = "cd... | class Solution:
def rotateString(self, s: str, goal: str) -> bool:
for x in range(len(s)):
s = s[-1] + s[:-1]
if (goal == s):
return True
return False | class Solution {
public boolean rotateString(String s, String goal) {
int n = s.length(), m = goal.length();
if (m != n) return false;
for (int offset = 0; offset < n; offset++) {
if (isMatch(s, goal, offset)) return true;
}
return false;
}
private boole... | class Solution {
public:
bool rotateString(string s, string goal) {
if(s.size()!=goal.size()){
return false;
}
string temp=s+s;
if(temp.find(goal)!=-1){
return true;
}
return false;
}
}; | var rotateString = function(s, goal) {
const n = s.length;
for(let i = 0; i < n; i++) {
s = s.substring(1) + s[0];
if(s === goal) return true;
}
return false;
}; | Rotate String |
There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the... | class Solution:
def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:
graph = defaultdict(list)
# build graph
for edge in edges:
graph[edge[0]].append((edge[1], edge[2]))
graph[edge[1]].append((edge[0], edge[2]))
q = ... | class Solution {
public int maximalPathQuality(int[] values, int[][] edges, int maxTime) {
int n = values.length;
List<int[]>[] adj = new List[n];
for (int i = 0; i < n; ++i) adj[i] = new LinkedList();
for (int[] e : edges) {
int i = e[0], j = e[1], t = e[2];
... | class Solution {
public:
int maximalPathQuality(vector<int>& values, vector<vector<int>>& edges, int maxTime) {
int n = values.size();
int res = values[0];
vector<vector<pair<int,int>>> graph(n);
for(int i=0;i<edges.size();i++)
{
graph[edges[i][0]].push_back({edge... | var maximalPathQuality = function(values, edges, maxTime) {
const adjacencyList = values.map(() => []);
for (const [node1, node2, time] of edges) {
adjacencyList[node1].push([node2, time]);
adjacencyList[node2].push([node1, time]);
}
const dfs = (node, quality, time, seen) => {
... | Maximum Path Quality of a Graph |
A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)
You are given some events [start, end), after each given event, return an integer k representing the maximum k-booking between all the previous events.
Implement the MyCalendarThree class:
... | import bisect
class MyCalendarThree:
def __init__(self):
self.events = []
def book(self, start: int, end: int) -> int:
L, R = 1, 0
bisect.insort(self.events, (start, L))
bisect.insort(self.events, (end, R))
res = 0
cnt = 0
for _, state in self.ev... | class MyCalendarThree {
TreeMap<Integer, Integer> map;
public MyCalendarThree() {
map = new TreeMap<>();
}
public int book(int start, int end) {
if(map.isEmpty()){
map.put(start, 1);
map.put(end,-1);
return 1;
}
//upvote if you like ... | class MyCalendarThree {
public:
map<int,int>mp;
MyCalendarThree() {
}
int book(int start, int end) {
mp[start]++;
mp[end]--;
int sum = 0;
int ans = 0;
for(auto it = mp.begin(); it != mp.end(); it++){
sum += it->second;
ans = max(ans,sum)... | var MyCalendarThree = function() {
this.intersections = [];
this.kEvents = 0;
};
/**
* @param {number} start
* @param {number} end
* @return {number}
*/
MyCalendarThree.prototype.book = function(start, end) {
let added = false;
for(let i = 0; i < this.intersections.length; i++) {
con... | My Calendar III |
You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.
A uni-value grid is a grid where all the elements of it are equal.
Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1.
 ... | class Solution:
def minOperations(self, grid: List[List[int]], x: int) -> int:
m = len(grid)
n = len(grid[0])
# handle the edge case
if m==1 and n==1: return 0
# transform grid to array, easier to operate
arr = []
for i in range(m):
arr+=grid[i... | class Solution {
public int minOperations(int[][] grid, int x) {
int[] arr = new int[grid.length * grid[0].length];
int index = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
arr[index++] = grid[i][j];
}
... | class Solution {
public:
int minOperations(vector<vector<int>>& grid, int x) {
vector<int>nums;
int m=grid.size(),n=grid[0].size();
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
nums.push_back(grid[i][j]);
sort(nums.begin(),nums.end());
int target=nums... | var minOperations = function(grid, x) {
let remainder = -Infinity, flatten = [], res = 0;
for(let i = 0;i<grid.length;i++){
for(let j = 0;j<grid[i].length;j++){
if(remainder === -Infinity)
remainder = grid[i][j] % x;
else if(remainder !== gr... | Minimum Operations to Make a Uni-Value Grid |
Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.
A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.
Example 1:
Input: root = [8,3,10,1,6,nul... | class Solution:
def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
self.max_diff = float('-inf')
def dfs(node,prev_min,prev_max):
if not node:
return
dfs(node.left,min(prev_min,node.val),max(prev_max,node.val))
dfs(node.right,min(... | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solutio... | class Solution {
private:
int maxDiff;
pair <int, int> helper(TreeNode* root) {
if (root == NULL) return {INT_MAX, INT_MIN};
pair <int, int> L = helper(root -> left), R = helper(root -> right);
pair <int, int> minMax = {min(L.first, R.first), max(L.second, R.second)};
if (minMax.... | var maxAncestorDiff = function(root) {
let ans = 0;
const traverse = (r = root, mx = root.val, mn = root.val) => {
if(!r) return;
ans = Math.max(ans, Math.abs(mx - r.val), Math.abs(mn - r.val));
mx = Math.max(mx, r.val);
mn = Math.min(mn, r.val);
traverse(r.left, mx, mn);... | Maximum Difference Between Node and Ancestor |
Let's play the minesweeper game (Wikipedia, online game)!
You are given an m x n char matrix board representing the game board where:
'M' represents an unrevealed mine,
'E' represents an unrevealed empty square,
'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, an... | class Solution:
def calMines(self,board,x,y):
directions = [(-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)]
mines = 0
for d in directions:
r, c = x+d[0],y+d[1]
if self.isValid(board,r,c) and (board[r][c] == 'M' or board[r][c] == 'X'):
min... | class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
int r = click[0];
int c = click[1];
if(board[r][c] == 'M')
{
board[r][c] = 'X';
return board;
}
dfs(board, r, c);
return board;
}
private void dfs(char... | class Solution {
public:
int m, n ;
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
if(board[click[0]][click[1]] == 'M'){
board[click[0]][click[1]] = 'X' ;
return board ;
}
else{
m = board.size(), n = board[0].size()... | var updateBoard = function(board, click) {
const [clickR, clickC] = click;
const traverseAround = ({ currentRow, currentCol, fun }) => {
for (let row = -1; row <= 1; row++) {
for (let col = -1; col <= 1; col++) {
fun(currentRow + row, currentCol + col);
}
}
};
const getMinesCount = (currentRow, curren... | Minesweeper |
You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:
Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equa... | class Solution:
def canMerge(self, trees: List[TreeNode]) -> TreeNode:
n = len(trees)
if n == 1: return trees[0]
value_to_root = {} # Map each integer root value to its node
appeared_as_middle_child = set() # All values appearing in trees but not in a curr or leaf
self.saw_c... | class Solution {
public TreeNode canMerge(List<TreeNode> trees) {
//Map root value to tree
HashMap<Integer, TreeNode> map = new HashMap<>();
for(TreeNode t : trees){
map.put(t.val, t);
}
// Merge trees
for(TreeNode t : trees){
if(map.containsK... | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), l... | var canMerge = function(trees) {
let Node={},indeg={}
// traverse the mini trees and put back pointers to their parents, also figure out the indegree of each node
let dfs=(node,leftparent=null,rightparent=null)=>{
if(!node)return
indeg[node.val]=indeg[node.val]||Number(leftparent!==null||rig... | Merge BSTs to Create Single BST |
You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.
Each plant needs a specific amount of water. You will water th... | class Solution:
def wateringPlants(self, plants: List[int], capacity: int) -> int:
result = 0
curCap = capacity
for i in range(len(plants)):
if curCap >= plants[i]:
curCap -= plants[i]
result += 1
else:
result += i * 2... | class Solution {
public int wateringPlants(int[] plants, int capacity) {
int count=0,c=capacity;
for(int i=0;i<plants.length;i++){
if(c>=plants[i]){
c-=plants[i];
count++;
}
else {
c=capacity;
count=c... | class Solution {
public:
int wateringPlants(vector<int>& plants, int capacity) {
int result = 0;
int curCap = capacity;
for (int i=0; i < plants.size(); i++){
if (curCap >= plants[i]){
curCap -= plants[i];
result++;
}
else{
result += i * 2 + 1;
curCap = capacity - plants[i];
}
... | var wateringPlants = function(plants, capacity) {
var cap = capacity;
var steps = 0;
for(let i = 0; i < plants.length;i++){
if(cap >= plants[i]){
steps = steps + 1;
}else{
cap = capacity;
steps = steps + (2 *i + 1);
}
cap = cap - plants[i];... | Watering Plants |
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:
Every element less than pivot appears before every element greater than pivot.
Every element equal to pivot appears in between the elements less than and greater than pivot.
The relat... | class Solution:
def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
left=[]
mid=[]
right=[]
for i in nums:
if(i<pivot):
left.append(i)
elif(i==pivot):
mid.append(i)
else:
right.append(i)
... | // Time complexity = 2n = O(n)
// Space complexity = O(1), or O(n) if the result array is including in the complexity analysis.
class Solution {
public int[] pivotArray(int[] nums, int pivot) {
int[] result = new int[nums.length];
int left = 0, right = nums.length - 1;
for(int i = 0; i < n... | class Solution {
public:
vector<int> pivotArray(vector<int>& nums, int pivot) {
int i = 0;
vector<int> res;
int cnt = count(nums.begin(), nums.end(), pivot);
while(--cnt >= 0) {
res.push_back(pivot);
}
for(int k = 0; k < nums.size(); k++) {
if(... | /**
* @param {number[]} nums
* @param {number} pivot
* @return {number[]}
*/
var pivotArray = function(nums, pivot) {
let n=nums.length;
//first Solution with 3 separet Array
let lessPivot=[]
let equalPivot=[]
let bigerPivot=[]
for(let i=0;i<n;i++){
if(nums[i]<pivot)lessPivot.push... | Partition Array According to Given Pivot |
A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.
For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "... | class Solution:
def areNumbersAscending(self, s):
nums = re.findall(r'\d+', s)
return nums == sorted(set(nums), key=int) | // Space Complexity: O(1)
// Time Complexity: O(n)
class Solution {
public boolean areNumbersAscending(String s) {
int prev = 0;
for(String token: s.split(" ")) {
try {
int number = Integer.parseInt(token);
if(number <= prev)
return fa... | class Solution {
public:
bool areNumbersAscending(string s) {
s.push_back(' '); // for last number calculation
int prev = -1;
string num;
for(int i = 0 ; i < s.size() ; ++i)
{
char ch = s[i];
if(isdigit(ch))
num += ch;
... | var areNumbersAscending = function(s) {
const numbers = [];
const arr = s.split(" ");
for(let i of arr) {
if(isFinite(i)) {
if(numbers.length > 0 && numbers[numbers.length - 1] >= i) {
return false;
}
numbers.push(+i);
}
}
return tr... | Check if Numbers Are Ascending in a Sentence |
There is a hidden integer array arr that consists of n non-negative integers.
It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].
You are given the encoded array. You are also given an integer first, ... | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
return [first] + [first:= first ^ x for x in encoded] | class Solution {
public int[] decode(int[] encoded, int first) {
int[] ans = new int[encoded.length + 1];
ans[0] = first;
for (int i = 0; i < encoded.length; i++) {
ans[i + 1] = ans[i] ^ encoded[i];
}
return ans;
}
} | class Solution {
public:
vector<int> decode(vector<int>& encoded, int first) {
vector<int> ans{first};
for(int x: encoded)
ans.push_back(first^=x);
return ans;
}
}; | var decode = function(encoded, first) {
return [first].concat(encoded).map((x,i,a)=>{return i===0? x : a[i] ^= a[i-1]});
}; | Decode XORed Array |
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.
Return the minimum number of op... | class Solution:
def minOperations(self, s: str) -> int:
count = 0
count1 = 0
for i in range(len(s)):
if i % 2 == 0:
if s[i] == '1':
count += 1
if s[i] == '0':
count1 += 1
else:
if ... | class Solution {
public int minOperations(String s) {
int count0 = 0; // changes required when the string starts from 0
int count1 = 0; // changes required when the string starts from 1
for(int i = 0; i < s.length(); i++){
// string starts with 1 => all chars at even places sho... | class Solution {
public:
int minOperations(string s) {
int n=s.size(), ans=0;
for(int i=0;i<n;i++)
{
if(s[i]-'0' != i%2)
ans++;
}
return min(ans, n-ans);
}
}; | /**
* @param {string} s
* @return {number}
*/
var minOperations = function(s) {
let counter1=0;
let counter2=0;
for(let i=0;i<s.length;i++){
if(i%2===0){
if(s[i]==="0"){
counter1++;
}
if(s[i]==="1"){
counter2++;
}
... | Minimum Changes To Make Alternating Binary String |
In a string s of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and "yy".
A group is identified by an interval [start, end], where start and end denote the start and e... | class Solution:
def largeGroupPositions(self, s: str) -> List[List[int]]:
i=0
c=1
prev=""
l=len(s)
ans=[]
while i<l:
if s[i]==prev:
c+=1
if (i==l-1) & (c>=3):
ans.append([i+1-c,i])
else:
... | class Solution {
public List<List<Integer>> largeGroupPositions(String s) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
int count = 1;
for (int i = 0; i < s.length() - 1; i++) {
// Increment the count until the next element... | class Solution {
public:
vector<vector<int>> largeGroupPositions(string s) {
vector<vector<int>> res;
int st = 0;
int en = 1;
while(en < s.size())
{
if(s[en] != s[st])
{
if(en-st >= 3)
{
... | // 77 ms, faster than 97.56%
// 45 MB, less than 87.81%
var largeGroupPositions = function(s) {
let re = /(.)\1{2,}/g;
let ans = [];
while ((rslt = re.exec(s)) !== null) {
ans.push([rslt.index, rslt.index + rslt[0].length-1]);
}
return ans;
}; | Positions of Large Groups |
Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.
An integer m is a divisor of n if there exists an integer k such that n = k * m.
Example 1:
Input: n = 2
Output: false
Explantion: 2 has only two divisors: 1 and 2.
Example 2:
Input: n = 4
Output: true
Explan... | import math
class Solution:
def isThree(self, n: int) -> bool:
primes = {3:1, 5:1, 7:1, 11:1, 13:1, 17:1, 19:1, 23:1, 29:1, 31:1, 37:1, 41:1, 43:1, 47:1, 53:1, 59:1, 61:1, 67:1, 71:1, 73:1, 79:1, 83:1, 89:1, 97:1}
if n == 4:
return True
else:
a = math.sqrt(n)
... | class Solution {
public boolean isThree(int n) {
if(n<4 ) return false;
int res = (int)Math.sqrt(n);
for(int i=2;i*i<n;i++){
if(res%i ==0) return false;
}
return true;
}} | class Solution {
public:
bool isPrime(int n) {
for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false;
return true;
}
bool isThree(int n) {
return n != 1 && n != 2 && (int)sqrt(n)*sqrt(n) == n && isPrime(sqrt(n));
}
}; | var isThree = function(n) {
var set = new Set();
for(var i = 1; i<=Math.sqrt(n) && set.size <= 3; i++)
{
if(n % i === 0)
{
set.add(i);
set.add(n / i);
}
}
return set.size===3;
}; | Three Divisors |
A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.
Given an array positions where positions[i] = [xi... | class Solution:
def getMinDistSum(self, positions: List[List[int]]) -> float:
n = len(positions)
if n == 1: return 0
def gradient(x,y):
ans = [0,0]
for i in range(n):
denom = math.sqrt(pow(x-positions[i][0],2)+pow(y-positions[i][1],2))
... | class Solution {
private static final double MIN_STEP = 0.0000001;
private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public double getMinDistSum(int[][] positions) {
double cx = 0, cy = 0;
int n = positions.length;
for (int[] pos: positions) {
... | class Solution {
public:
const double MIN_STEP = 0.000001; // With 0.00001 not AC
const int dx[4] = {0, 0, 1,-1};
const int dy[4] = {1, -1, 0, 0};
double totalDist(vector<vector<int>>& positions, double cx, double cy) {
double dist = 0;
for (auto p : positions) {
dist += hy... | /**
* @param {number[][]} positions
* @return {number}
*/
var getMinDistSum = function(positions) {
/**
identify the vertical range and horizontal range
start from the center of positions
calc the distance
test the 4 direction with a certain step
if any distance is cl... | Best Position for a Service Centre |
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.
The test cases are generated so that the answer can fit in a 32-bit integer.
Example 1:
Input: nums = [1,2,3], target = 4
Output: 7
Explanation:
The possible combination... | class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
dp = [0] * (target+1)
dp[0] = 1
for i in range(1, target+1):
for num in nums:
num_before = i - num
if num_before >= 0:
dp[i] += dp[num_before]
... | class Solution {
public int combinationSum4(int[] nums, int target) {
Integer[] memo = new Integer[target + 1];
return recurse(nums, target, memo);
}
public int recurse(int[] nums, int remain, Integer[] memo){
if(remain < 0) return 0;
if(memo[remain] != null) re... | class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<unsigned int> dp(target+1, 0);
dp[0] = 1;
for (int i = 1; i <= target; i++) {
for (auto x : nums) {
if (x <= i) {
dp[i] += dp[i - x];
}
... | var combinationSum4 = function(nums, target) {
const dp = Array(target + 1).fill(0);
nums.sort((a,b) => a - b);
for(let k=1; k <= target; k++) {
for(let n of nums) {
if(k < n) break;
dp[k] += (k == n) ? 1 : dp[k-n];
}
}
return dp[target];
}; | Combination Sum IV |
You are given an array of integers distance.
You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.... | class Solution:
def isSelfCrossing(self, x):
n = len(x)
if n < 4: return False
for i in range(3, n):
if x[i] >= x[i-2] and x[i-1] <= x[i-3]: return True
if i >= 4 and x[i-1]==x[i-3] and x[i]+x[i-4]>=x[i-2]: return True
if i >= 5 and 0<=x[i-2]-x[i-4]<=x[i] ... | class Solution {
public boolean isSelfCrossing(int[] x) {
boolean arm = false;
boolean leg = false;
for (int i = 2; i < x.length; ++i) {
int a = f(x, i - 2) - f(x, i - 4);
int b = f(x, i - 2);
if (arm && x[i] >= b) return true; // cross [i - 2]
if (leg && x[i] >= a && a > 0) return true; // cross [i - 4]
... | class Solution {
public:
bool isSelfCrossing(vector<int>& distance) {
if (distance.size() <= 3) return false; //only can have intersection with more than 4 lines
distance.insert(distance.begin(), 0); //for the edge case: line i intersect with line i-4 at (0, 0)
for (int i = 3; i < distance.... | class Solution {
public boolean isSelfCrossing(int[] x) {
boolean arm = false;
boolean leg = false;
for (int i = 2; i < x.length; ++i) {
int a = f(x, i - 2) - f(x, i - 4);
int b = f(x, i - 2);
if (arm && x[i] >= b) return true; // cross [i - 2]
if (leg && x[i] >= a && a > 0) return true; // cross [i - 4]
... | Self Crossing |
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node.
The kth ancestor of a tree node is the kth node in the path from that node to the root node.
Implement the T... | from math import ceil, log2
from typing import List
NO_PARENT = -1
class TreeAncestor:
def __init__(self, n: int, parent: List[int]):
self.parent = [[NO_PARENT] * n for _ in range(ceil(log2(n + 1)))]
self.__initialize(parent)
def __initialize(self, parent: List[int]):
self.parent[0], ... | class TreeAncestor {
int n;
int[] parent;
List<Integer>[] nodeInPath;
int[] nodeIdxInPath;
public TreeAncestor(int n, int[] parent) {
this.n = n;
this.parent = parent;
nodeInPath = new ArrayList[n];
nodeIdxInPath = new int[n];
fill();
}
private void ... | class TreeAncestor {
public:
//go up by only powers of two
vector<vector<int>> lift ;
TreeAncestor(int n, vector<int>& parent) {
lift.resize(n,vector<int>(21,-1)) ;
//every node's first ancestor is parent itself
for(int i = 0 ; i < n ; ++i ) lift[i][0] = parent[i] ;
for(int ... | /**
* @param {number} n
* @param {number[]} parent
*/
var TreeAncestor = function(n, parent) {
this.n = n;
this.parent = parent;
};
/**
* @param {number} node
* @param {number} k
* @return {number}
*/
/*
Qs:
1. Is the given tree a binary tree or n-ary tree?
2. Can k be greater than possible (the tota... | Kth Ancestor of a Tree Node |
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Example 1:
Input: grid = [[4,3... | class Solution:
digits = {1, 2, 3, 4, 5, 6, 7, 8, 9}
@classmethod
def magic_3_3(cls, square: List[List[int]]) -> bool:
if set(sum(square, [])) != Solution.digits:
return False
sum_row0 = sum(square[0])
for r in range(1, 3):
if sum(square[r]) != sum_row0:
... | class Solution {
public int numMagicSquaresInside(int[][] grid) {
int n=grid.length,m=grid[0].length,count=0;
for(int i=0;i<n-2;i++)
{
for(int j=0;j<m-2;j++)
{
if(sum(i,j,grid))
count++;
}
}
return count;
}
public boolean sum(int x,int y,int[][] grid)
{
int sum=grid[x][y]+grid[x][y+1]+... | class Solution {
public:
int numMagicSquaresInside(vector<vector<int>>& grid) {
int result = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[i].size() ; j++){
if(isMagicSquare(grid, i, j)){
result++;
}
}
... | var numMagicSquaresInside = function(grid) {
let res = 0;
for(let i = 0; i < grid.length - 2; i++){
for(let j = 0; j < grid[0].length - 2; j++){
//only check 4
if(grid[i][j]+grid[i][j+1]+grid[i][j+2]==15
&& grid[i][j]+grid[i+1][j]+grid[i+2][j]==15
&& grid[i][j]... | Magic Squares In Grid |
A string is a valid parentheses string (denoted VPS) if it meets one of the following:
It is an empty string "", or a single character not equal to "(" or ")",
It can be written as AB (A concatenated with B), where A and B are VPS's, or
It can be written as (A), where A is a VPS.
We can similarly define the nest... | class Solution:
def maxDepth(self, s: str) -> int:
ans = cur = 0
for c in s:
if c == '(':
cur += 1
ans = max(ans, cur)
elif c == ')':
cur -= 1
return ans | class Solution {
public int maxDepth(String s) {
int count = 0; //count current dept of "()"
int max = 0; //count max dept of "()"
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
count++;
} else if (s.charAt(i) == ')') {
... | class Solution {
public:
int maxDepth(string s) {
int maxi=0,curr=0;
for(int i=0;i<s.size();i++){
if(s[i]=='('){
maxi=max(maxi,++curr);
}else if(s[i]==')'){
curr--;
}
}
return maxi;
}
}; | var maxDepth = function(s) {
let maxCount = 0, count = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') {
maxCount = Math.max(maxCount, ++count);
} else if (s[i] === ')') {
count--;
}
}
return maxCount;
}; | Maximum Nesting Depth of the Parentheses |
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given a... | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
class UnionFind:
def __init__(self):
self.parents = {}
self.ranks = {}
def insert(self, x):
if x not in self.parents:
... | class Solution {
public List<Integer> findAllPeople(int n, int[][] meetings, int firstPerson) {
// create <time, index> map
Map<Integer, List<Integer>> timeToIndexes = new TreeMap<>();
int m = meetings.length;
for (int i = 0; i < m; i++) {
timeToIndexes.putIfAbsent(meetings[i... | class Solution {
public:
vector<int> findAllPeople(int n, vector<vector<int>>& meetings, int firstPerson) {
vector<int> res;
set<int> ust;
ust.insert(0);
ust.insert(firstPerson);
map<int,vector<pair<int,int>>> mp;
for (auto &m : meetings) {
mp[m[2]].push_b... | var findAllPeople = function(n, meetings, firstPerson) {
const timeToMeeting = mapSortedTimeToMeetings(meetings);
const peopleThatCurrentlyHaveSecret = new Set([0, firstPerson]);
for (const peopleInMeetings of timeToMeeting.values()) {
const personToMeetingsWithPeople =
mapPeopleToPeopl... | Find All People With Secret |
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
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.... | class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
def lcs(ind1,ind2):
prev=[0 for i in range(ind2+1)]
curr=[0 for i in range(ind2+1)]
for i in range(1,ind1+1):
for j in range(1,ind2+1):
if t... | class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1.charAt(i - 1) ==... | class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int dp[1001][1001] = {0};
for(int i = 1; i <= text1.size(); i++)
for(int j = 1; j <= text2.size(); j++)
if(text1[i-1] == text2[j-1]) dp[i][j] = 1 + dp[i-1][j-1];
else dp[i]... | /**
* @param {string} text1
* @param {string} text2
* @return {number}
*/
let memo
const dp=(a,b,i,j)=>{
if(i===0||j===0)return 0;
if(memo[i][j]!=-1)return memo[i][j];
if(a[i-1]===b[j-1]){
return memo[i][j]= 1+ dp(a,b,i-1,j-1);
}else{
return memo[i][j]=Math.max(dp(a,b,i-1,j),dp(a,b,i... | Longest Common Subsequence |
A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows.
originalText is placed first in a top-left to bottom-right manner.
The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, u... | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
n = len(encodedText)
cols = n // rows
step = cols + 1
res = ""
for i in range(cols):
for j in range(i, n, step):
res += encodedText[j]
ret... | class Solution {
public String decodeCiphertext(String str, int rows) {
//first find column size!!
int cols=str.length()/rows;
StringBuilder res=new StringBuilder(),new_res=new StringBuilder();;
for(int i=0;i<cols;i++) {
//iterating diagonally!!
for(int j=i;j... | class Solution {
public:
string decodeCiphertext(string encodedText, int rows) {
int n = encodedText.size();
// Determining the number of columns
int cols = n / rows;
vector<vector<char>> mat(rows, vector<char>(cols, ' '));
int i = 0, j = 0;
int k = 0;
strin... | var decodeCiphertext = function(encodedText, rows) {
const numColumns = encodedText.length / rows;
const stringBuilder = [];
let nextCol = 1;
let row = 0;
let col = 0;
let index = 0
while (index < encodedText.length) {
stringBuilder.push(encodedText[index]);
if (row === rows ... | Decode the Slanted Ciphertext |
Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
Example 1:
Input: s = "aab"
Output: "aba"
Example 2:
Input: s = "aaab"
Output: ""
Constraints:
1 <= s.length <= 500
s cons... | class Solution:
def reorganizeString(self, s: str) -> str:
c = Counter(s) # for counting the distinct element
pq = []
for k,v in c.items(): heapq.heappush(pq,(-v,k)) #multipy by -1 to make max heap
ans = ''
while pq :
c, ch = heapq.heappop(pq)
if ans and ans[-1] == ch:
if not pq: return '' // ... | class Solution {
public String reorganizeString(String s) {
StringBuilder ans=new StringBuilder("");
char[] charArray=new char[s.length()];
Map<Character,Integer> hashMap=new HashMap<>();
Queue<CharOccurence> queue=new PriorityQueue<>((a,b)->b.occurence-a.occurence);
charArr... | class Solution {
public:
string reorganizeString(string s) {
// Step1: insert elements to the map so that we will get the frequency
unordered_map<char, int> mp;
for(auto i: s){
mp[i]++;
}
//Step2: Create a max heap to store all the elements accor... | var reorganizeString = function(s) {
const charMap = {};
const res = [];
// Store the count of each char
for (let char of s) {
charMap[char] = (charMap[char] || 0) + 1;
}
// Sort in descending order by count
const sortedMap = Object.entries(charMap).sort((a, b) => b[1] - a[1]);
... | Reorganize String |
There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.
Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.
Alice ... | class Solution:
def winnerOfGame(self, s: str) -> bool:
a = b = 0
for i in range(1,len(s)-1):
if s[i-1] == s[i] == s[i+1]:
if s[i] == 'A':
a += 1
else:
b += 1
return a>b | class Solution {
public boolean winnerOfGame(String colors) {
int cntA=0,cntB=0;
for(int i=1;i<colors.length()-1;i++){
if(colors.charAt(i)=='A'&&colors.charAt(i-1)=='A'&&colors.charAt(i+1)=='A')cntA++;
if(colors.charAt(i)=='B'&&colors.charAt(i-1)=='B'&&colors.charAt(i+1)=='B... | class Solution {
public:
bool winnerOfGame(string colors) {
if (colors.size() < 3) return false;
int a = 0, b = 0;
for (int i = 0; i < colors.size()-2; i++) {
if (colors.substr(i, 3) == "AAA") a++;
else if (colors.substr(i, 3) == "BBB") b++;
}
return a... | var winnerOfGame = function(colors) {
const n = colors.length;
const stack = [];
let alice = 0;
let bob = 0;
for (let i = 0; i < n; ++i) {
const char = colors[i];
if (stack.length > 1 && stack[stack.length - 1] === char && stack[stack.length - 2] === char) {
... | Remove Colored Pieces if Both Neighbors are the Same Color |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.