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 |
End of preview. Expand in Data Studio
This dataset contains: problems and solutions in Leetcode, crawled from: https://github.com/AnasImloul/Leetcode-Solutions
The format of data:
- title: title of the problem
- algo_input: the description of the problem
- solution_py: the solution in Python
- solution_js: the solution in Js
- solution_java: the solution in Java
- solution_c: the solution in C
- Downloads last month
- 11