algo_input stringlengths 240 3.91k | solution_py stringlengths 10 6.72k | solution_java stringlengths 87 8.97k | solution_c stringlengths 10 7.38k | solution_js stringlengths 10 4.56k | title stringlengths 3 77 |
|---|---|---|---|---|---|
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
prev=head
cur=head
while cur is not None:
if cur.... | class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode result = head;
while (head.next != null) {
if (head.next.val == val) {
head.next = head.next.next;
} else {
... | class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *prv,*cur,*temp;
while(head && head->val==val){
cur=head;
head=head->next;
delete(cur);
}
if(head==NULL) return head;
prv=head;
cur=head->next;
... | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
if(!he... | Remove Linked List Elements |
There are 8 prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
Note t... | class Solution:
def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:
patternMatch=defaultdict(int) # pattern match
totalPrisons=8 # totalPrisons
cells= [ str(c) for c in (cells)] # into char type
for d in range(1,n+1):
tempCell=[]
tempCell.append... | class Solution {
public int[] prisonAfterNDays(int[] cells, int n) {
// # Since we have 6 cells moving cells (two wil remain unchaged at anytime)
// # the cycle will restart after 14 iteration
// # 1- The number of days if smaller than 14 -> you brute force O(13)
// # 2- The number ... | class Solution {
public:
vector<int> prisonAfterNDays(vector<int>& cells, int n) {
//since there are only a 2**6 number of states and n can go to 10**9
//this means that there is bound to be repetition of states
int state=0;
//making the initial state bitmask
for(int i=0;i<ce... | /**
* @param {number[]} cells
* @param {number} n
* @return {number[]}
*/
var prisonAfterNDays = function(cells, n) {
const set = new Set()
let cycleDuration = 0
while(n--) {
const nextCells = getNextCells(cells)
// 1. Get cycle length
if(!set.has(String(nextCells))){
... | Prison Cells After N Days |
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:
You will pick any pizza slice.
Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.
Your friend Bob will pick the next slice in the clockwise direction of your pick.
Repe... | class Solution:
def maxSizeSlices(self, slices: List[int]) -> int:
** #This solve function mainly on work on the idea of A Previous dp problem House Robber II
#If we take the first slice then we cant take the second slice and vice versa**
def solve(slices,start,end,n,dp):
if start>end or n=... | class Solution {
public int maxSizeSlices(int[] slices) {
int n = slices.length;
return Math.max(helper(slices, n/3, 0, n - 2), helper(slices, n/3, 1, n - 1));
}
private int helper(int[] slices, int rounds, int start, int end) {
int n = end - start + 1, max = 0;
int[][][... | class Solution {
public:
int dp[501][501];
int solve(vector<int>&v , int i ,int count ){
if( i >= v.size() || count > v.size()/3 ) return 0 ;
if(dp[i][count] != -1 ) return dp[i][count];
int pick = v[i] + solve(v,i+2,count+1) ;
int notPick =... | var maxSizeSlices = function(slices) {
const numSlices = slices.length / 3;
const len = slices.length - 1;
const dp = new Array(len).fill(null).map(() => new Array(numSlices + 1).fill(0));
const getMaxTotalSlices = (pieces) => {
// the max for 1 piece using only the first slice is itself
... | Pizza With 3n Slices |
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an isl... | from queue import Queue
from typing import List
class Solution:
def __init__(self):
self.directions = [[-1, 0], [0, 1], [1, 0], [0, -1]]
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
[rows, cols] = [len(grid), len(grid[0])]
ans = 0
visited: List[List[bool]] = [[Fal... | class Solution {
public int maxAreaOfIsland(int[][] grid) {
final int rows=grid.length;
final int cols=grid[0].length;
final int[][] dirrections=new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
Map<String,List<int[]>> adj=new HashMap<>();
boolean[][] visited=new boolean[rows][cols];
Queu... | class Solution {
public:
int cal(vector<vector<int>>& grid,int i,int j,int& m,int& n){
if(i==m || j==n || i<0 || j<0 || grid[i][j]==0)
return 0;
grid[i][j]=0;
return 1+cal(grid,i,j+1,m,n)+cal(grid,i+1,j,m,n)+cal(grid,i,j-1,m,n)+cal(grid,i-1,j,m,n);
}
int maxAreaOfIsland(v... | var maxAreaOfIsland = function(grid) {
let result = 0;
const M = grid.length;
const N = grid[0].length;
const isOutGrid = (m, n) => m < 0 || m >= M || n < 0 || n >= N;
const island = (m, n) => grid[m][n] === 1;
const dfs = (m, n) => {
if (isOutGrid(m, n) || !island(m, n)) return 0;
... | Max Area of Island |
Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".
A string is palindromic if it reads the same forward and backward.
Example 1:
Input: words = ["abc","car","ada","racecar","cool"]
Output: "ada"
Explanation: The first strin... | class Solution:
def firstPalindrome(self, words):
for word in words:
if word == word[::-1]: return word
return "" | class Solution {
public String firstPalindrome(String[] words) {
for (String s : words) {
StringBuilder sb = new StringBuilder(s);
if (s.equals(sb.reverse().toString())) {
return s;
}
}
return "";
}
} | class Solution {
bool isPalindrome(string str){
int i=0 ;
int j=str.length()-1;
while( i<= j ){
if( str[i] != str[j] )
return false;
i++;
j--;
}
return true;
}
public:
string firstPalindrome(vector<string>& words) {
... | var firstPalindrome = function(words) {
for (const word of words) {
if (word === word.split('').reverse().join('')) return word;
}
return '';
}; | Find First Palindromic String in the Array |
You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].
You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:
The first element in s[k] starts with the selection of the element nums[k] of index =... | class Solution:
def arrayNesting(self, nums: List[int]) -> int:
max_len = 0
visited = set()
def dfs(nums, index, dfs_visited):
if index in dfs_visited:
return len(dfs_visited)
# add the index to dfs_visited and visited
visited.... | class Solution {
public int arrayNesting(int[] nums) {
int res=0;
boolean[] visited = new boolean[nums.length];
for(int i=0;i<nums.length;i++){
if(!visited[i]){
int len = dfs(nums,i,visited);
res = Math.max(res,len);
}
}
... | class Solution {
public:
int dfs(vector<int>&nums,int ind,int arr[],int res)
{
if(arr[ind]==1)
return res;
res++;
arr[ind]=1;
return dfs(nums,nums[ind],arr,res);
}
int arrayNesting(vector<int>& nums) {
int arr[nums.size()],ans=0;
for(i... | var arrayNesting = function(nums) {
return nums.reduce((result, num, index) => {
let count = 1;
while (nums[index] !== index) {
const next = nums[index];
[nums[index], nums[next]] = [nums[next], nums[index]];
count += 1;
}
return Math.max(result, count);
}, 0);
}; | Array Nesting |
Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.
Example 1:
Input: n = 5
Output: 2
Explanation: 5 = 2 + 3
Example 2:
Input: n = 9
Output: 3
Explanation: 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: n = 15
Output: 4
Explanation: 15 = 8 + 7 = 4 + 5 + 6 =... | # For every odd divisor d of n, there's exactly one sum of length d, e.g.
#
# 21 = 3 * 7 = 6 + 7 + 8.
#
# Also, every odd length sum is of this form, since the middle value is average,
# and the sum is just (number of elements) * (average) = d * n/d.
#
# For even length sums, the average is a half-integer
#
# 2... | class Solution {
public int consecutiveNumbersSum(int n) {
final double eightN = (8d * ((double) n)); // convert to double because 8n can overflow int
final int maxTriangular = (int) Math.floor((-1d + Math.sqrt(1d + eightN)) / 2d);
int ways = 1;
int triangular = 1;
for (int ... | class Solution {
public:
int consecutiveNumbersSum(int n) {
int count = 0;
for(int i = 2 ; i < n ; i++){
int sum_1 = i*(i+1)/2;
if(sum_1 > n)
break;
if((n-sum_1)%i == 0)
count++;
}
return count+1;
}
}; | var consecutiveNumbersSum = function(n) {
let count = 1;
for (let numberOfTerms = 2; numberOfTerms < Math.sqrt(2*n) + 1; numberOfTerms++) {
let startNumber = (n - numberOfTerms * (numberOfTerms - 1) / 2) / numberOfTerms;
if (Number.isInteger(startNumber) && startNumber !== 0) {
count... | Consecutive Numbers Sum |
You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.
Return the maximum score you can get by erasing exactly one subarray.
An array b is called to be a subarray of a if it forms a c... | class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
max_sum = 0
seen = set()
for l in range(len(nums)):
seen.clear()
curr_sum = 0
r = l
while r < len(nums):
if nums[r] in seen:
break
... | class Solution {
public int maximumUniqueSubarray(int[] nums) {
short[] nmap = new short[10001];
int total = 0, best = 0;
for (int left = 0, right = 0; right < nums.length; right++) {
nmap[nums[right]]++;
total += nums[right];
while (nmap[nums[right]] > 1)... | class Solution {
public:
int maximumUniqueSubarray(vector<int>& nums) {
int curr_sum=0, res=0;
//set to store the elements
unordered_set<int> st;
int i=0,j=0;
while(j<nums.size()) {
while(st.count(nums[j])>0) {
//Removing the ith element untill w... | var maximumUniqueSubarray = function(nums) {
let nmap = new Int8Array(10001), total = 0, best = 0
for (let left = 0, right = 0; right < nums.length; right++) {
nmap[nums[right]]++, total += nums[right]
while (nmap[nums[right]] > 1)
nmap[nums[left]]--, total -= nums[left++]
be... | Maximum Erasure Value |
HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.
The special characters and their entities for HTML are:
Quotation Mark: the entity is &quot; and symbol character is ".
Single Quote Mark: the entity is &apos; and... | class Solution:
def entityParser(self, text: str) -> str:
d = {""" : '"' , "'":"'" , "&" : "&" , ">" : ">" , "<":"<" , "⁄" : "/"}
ans = ""
i = 0
while i < len(text):
bag = ""
#condition if find ... | class Solution {
public String entityParser(String text) {
return text.replace(""","\"").replace("'","'").replace(">",">").replace("<","<").replace("⁄","/").replace("&","&");
}
} | class Solution {
public:
string entityParser(string text) {
map<string,char>mp;
mp["""] = '\"';
mp["'"] = '\'';
mp["&"] = '&';
mp[">"] = '>';mp["<"]='<';
mp["⁄"] = '/';
for(int i =0;i<text.size();i++){
if(text[i]=... | /**
* @param {string} text
* @return {string}
*/
var entityParser = function(text) {
const entityMap = {
'"': `"`,
''': `'`,
'&': `&`,
'>': `>`,
'<': `<`,
'⁄': `/`
}
stack = [], entity = "";
for(const char of text) {
... | HTML Entity Parser |
Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.
Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the f... | class Solution(object):
def isPrefixOfWord(self, sentence, searchWord):
"""
:type sentence: str
:type searchWord: str
:rtype: int
"""
word_list = sentence.split()
counter = 0
for word in sentence.split():
counter+=1
if searchWor... | class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
if(!sentence.contains(searchWord))
return -1;
boolean y=false;
String[] str=sentence.split(" ");
for(int i=0;i<str.length;i++){
if(str[i].contains(searchWord)){
f... | class Solution {
public:
int isPrefixOfWord(string s, string sw) {
stringstream ss(s);
string temp;
int i=1;
while(ss>>temp) {
if(temp.compare(0, sw.size(),sw)==0) return i;
i++;
}
return -1;
}
}; | var isPrefixOfWord = function(sentence, searchWord) {
let arr = sentence.split(' ');
for (let i = 0; i < arr.length; i++) {
let word = arr[i];
if (word.startsWith(searchWord)) return i + 1;
}
return -1;
}; | Check If a Word Occurs As a Prefix of Any Word in a Sentence |
There are three stones in different positions on the X-axis. You are given three integers a, b, and c, the positions of the stones.
In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the... | class Solution:
def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
a,b,c = sorted([a,b,c])
d1 = abs(b-a)-1
d2 = abs(c-b)-1
mi = 2
if d1 == 0 and d2 == 0: mi = 0
elif d1 <= 1 or d2 <= 1: mi =1
ma = c - a - 2
return [mi,ma] | class Solution {
public int[] numMovesStones(int a, int b, int c) {
int[] arr ={a,b,c};
int[] arr2 = {a,b,c};
int maximum = findMaximum(arr);
int minimum = findMinimum(maximum,arr2);
return new int[]{minimum,maximum};
}
public int findMaximum(int[] arr){
Array... | class Solution {
public:
vector<int> numMovesStones(int a, int b, int c) {
vector<int> arr = {a, b, c};
sort(arr.begin(), arr.end());
// find minimum moves
int mini = 0;
if(arr[1] - arr[0] == 1 && arr[2] - arr[1] == 1)
{
mini = 0;
}
e... | var numMovesStones = function(a, b, c) {
const nums = [a, b, c];
nums.sort((a, b) => a - b);
const leftGap = nums[1] - nums[0] - 1;
const rightGap = nums[2] - nums[1] - 1;
const maxMoves = leftGap + rightGap;
if (leftGap == 0 && rightGap == 0) return [0, 0];
if (leftGap > 1 && rightGap >... | Moving Stones Until Consecutive |
Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 2
Output: 2
Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals ... | '''
greedy, prefix sum with hashtable
O(n), O(n)
'''
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
# hash set to record previously encountered prefix sums
prefix_sums = {0}
res = prefix_sum = 0
for num in nums:
prefix_sum += nu... | class Solution {
public int maxNonOverlapping(int[] nums, int target) {
Map<Integer, Integer> valToPos = new HashMap<>();
int sums = 0;
int count = 0;
int lastEndPos = 0;
valToPos.put(0, 0);
for (int i = 0; i < nums.length; i++) {
sums += nums[i];
... | class Solution {
public:
unordered_map<int,int> mpp ;
int maxNonOverlapping(vector<int>& nums, int target) {
int sum = 0 , ways = 0 , prev = INT_MIN ;
mpp[0] = -1 ;
for(int i = 0 ; i < nums.size() ; ++i ){
sum += nums[i] ;
if(mpp.find(sum - target) != end(mpp) an... | var maxNonOverlapping = function(nums, target) {
const seen = new Set();
let total = 0, result = 0;
for(let n of nums) {
total += n;
if(total === target || seen.has(total - target)) {
total = 0;
result++;
seen.clear()
} else seen.add(... | Maximum Number of Non-Overlapping Subarrays With Sum Equals Target |
You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.
However, there are city restrictions on the heights of the new buildings:
The height of each building must be a non-negative integer.
The height of the first building must be 0.
The height differenc... | class Solution:
def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:
arr = restrictions
arr.extend([[1,0],[n,n-1]])
arr.sort()
n = len(arr)
for i in range(1,n):
arr[i][1] = min(arr[i][1], arr[i-1][1]+arr[i][0]-arr[i-1][0])
for i in range(n-... | class Solution {
public int maxBuilding(int n, int[][] restrictions) {
List<int[]> list=new ArrayList<>();
list.add(new int[]{1,0});
for(int[] restriction:restrictions){
list.add(restriction);
}
Collections.sort(list,new IDSorter());
if(list.get(list.size... | class Solution {
public:
int maxBuilding(int n, vector<vector<int>>& restrictions) {
restrictions.push_back({1, 0});
restrictions.push_back({n, n-1});
sort(restrictions.begin(), restrictions.end());
for (int i = restrictions.size()-2; i >= 0; --i) {
restrictions[i][1] =... | /**
* @param {number} n
* @param {number[][]} restrictions
* @return {number}
*/
var maxBuilding = function(n, restrictions) {
let maxHeight=0;
restrictions.push([1,0]);//Push extra restriction as 0 for 1
restrictions.push([n,n-1]);//Push extra restrition as n-1 for n
restrictions.sort(function(a,b)... | Maximum Building Height |
Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:
Players take turns placing characters into empty squares ' '.
The first player A always places 'X' characters, while the second player B always places 'O' characters.
'X' and 'O' characters are always placed into empty squa... | class Solution:
def tictactoe(self, moves: List[List[int]]) -> str:
wins = [
[(0, 0), (0, 1), (0, 2)],
[(1, 0), (1, 1), (1, 2)],
[(2, 0), (2, 1), (2, 2)],
[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)],
... | /**
Here is my solution :
Time Complexity O(M)
Space Complaexity O(1)
*/
class Solution {
public String tictactoe(int[][] moves) {
int [][] rcd = new int[3][3]; // rcd[0] --> rows , rcd[1] --> columns , rcd[2] --> diagonals
for(int turn =0 ; turn < moves.length ; turn++){
... | class Solution {
public:
string tictactoe(vector<vector<int>>& moves)
{
vector<vector<char>> grid(3,vector<char>(3));
char val='x';
for(auto &p:moves)
{
grid[p[0]][p[1]]=val;
val=val=='x'?'o':'x';
}
for (int i = 0; i < 3; i++){
... | /**
* @param {number[][]} moves
* @return {string}
*/
let validate = (arr) => {
let set = [...new Set(arr)];
return set.length == 1 && set[0] != 0;
}
var tictactoe = function(moves) {
let grid = [[0,0,0],[0,0,0],[0,0,0]];
for(let i in moves){
let [x,y] = moves[i]
grid[x][y] = (i % 2 ... | Find Winner on a Tic Tac Toe Game |
You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds.
For example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds, its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 second... | class Solution:
def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:
# by observation, we can try to find out the optimal usage within certain numLaps
# use DP
# the optimal usage of this lap = min(change tire , no change)
# dp(laps) = min( dp(la... | class Solution {
int changeTime;
public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) {
this.changeTime = changeTime;
int[] minTime = new int[numLaps + 1];
Arrays.fill(minTime, Integer.MAX_VALUE);
for (int[] tire : tires){
populateMinTime(tire, mi... | class Solution {
public:
int minimumFinishTime(vector<vector<int>>& tires, int changeTime, int numLaps) {
int n = tires.size();
// to handle the cases where numLaps is small
// without_change[i][j]: the total time to run j laps consecutively with tire i
vector<vector<int>> without_ch... | var minimumFinishTime = function(tires, changeTime, numLaps) {
const n = tires.length
const smallestTire = Math.min(...tires.map(t => t[1]))
const maxSameTire = Math.floor(Math.log(changeTime) / Math.log(smallestTire)) + 1
const sameTireLast = Array(n).fill(0)
// DP array tracking what is the min c... | Minimum Time to Finish the Race |
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes have no... | class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
left_set=set(leftChild)
right_set=set(rightChild)
que=[]
for i in range(n):
if i not in left_set and i not in right_set:
que.append... | import java.util.Arrays;
class Solution {
static class UF {
int[] parents;
int size;
UF(int n) {
parents = new int[n];
size = n;
Arrays.fill(parents, -1);
}
int find(int x) {
if (parents[x] == -1) {
return x;
}
return parents[x] = find(parents[x]);... | class Solution {
public:
int find_parent(vector<int>&parent,int x){
if(parent[x]==x)
return x;
return parent[x]=find_parent(parent,parent[x]);
}
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
vector<int> parent(n);
for(int i=0;i... | var validateBinaryTreeNodes = function(n, leftChild, rightChild) {
// find in-degree for each node
const inDeg = new Array(n).fill(0);
for(let i = 0; i < n; ++i) {
if(leftChild[i] !== -1) {
++inDeg[leftChild[i]];
}
if(rightChild[i] !== -1) {
++inDeg[rightChil... | Validate Binary Tree Nodes |
Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:
Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.
Find the next largest valu... | class Solution:
def reductionOperations(self, nums: List[int]) -> int:
return sum(accumulate(c for _,c in sorted(Counter(nums).items(), reverse=True)[:-1])) | class Solution {
public int reductionOperations(int[] nums) {
Map<Integer, Integer> valMap = new TreeMap<>(Collections.reverseOrder());
for (int i=0; i<nums.length; i++)
valMap.put(nums[i], valMap.getOrDefault(nums[i], 0) + 1);
int mapSize = valMap.size();
int opsCount ... | class Solution {
public:
int reductionOperations(vector<int>& nums) {
int n = nums.size();
map<int, int> mp;
for(int i = 0; i < n; i ++) {
mp[nums[i]] ++; // storing the frequency
}
int ans = 0;
int pre = 0;
for (auto ... | /**
* @param {number[]} nums
* @return {number}
*/
var reductionOperations = function(nums) {
nums.sort((a,b)=>a-b);
let count = 0;
for(let i = nums.length - 1;i>0;i--)
if(nums[i] !== nums[i-1])
count += nums.length - i
return count
}; | Reduction Operations to Make the Array Elements Equal |
You are given a binary array nums and an integer k.
A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.
Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return ... | class Solution:
def minKBitFlips(self, nums: List[int], k: int) -> int:
flips = [0]*len(nums)
csum = 0
for left in range(0, len(nums)-k+1):
if (nums[left] + csum) % 2 == 0:
flips[left] += 1
csum += 1
if left >= k-1:
csu... | class Solution {
public int minKBitFlips(int[] nums, int k) {
int target = 0, ans = 0;;
boolean[] flip = new boolean[nums.length+1];
for (int i = 0; i < nums.length; i++){
if (flip[i]){
target^=1;
}
if (i<nums.length-k+1&&nums[i]==target){
... | class Solution {
public:
int minKBitFlips(vector<int>& nums, int k) {
int n = nums.size();
int flips = 0; // flips on current positions
vector<int> flip(n+1,0); // to set end pointer for a flip i.e i+k ->-1
int ops = 0; // ... | var minKBitFlips = function(nums, k) {
let count = 0
for(let i=0; i<nums.length; i++){
if (nums[i] == 0){
for(let j=0; j<k && i+k <= nums.length; j++){
nums[i+j] = 1 - nums[i+j]
}
count++
}
}
return nums.every(n => n ==1) ... | Minimum Number of K Consecutive Bit Flips |
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.
For example, for arr = [2,3,4], the median is 3.
For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
Implement the MedianFinder class... | class MedianFinder:
def __init__(self):
self.min_hp = []
self.max_hp = []
def addNum(self, num: int) -> None:
if len(self.min_hp) == len(self.max_hp):
if len(self.max_hp) and num<-self.max_hp[0]:
cur = -heapq.heappop(self.max_hp)
heap... | class MedianFinder {
PriorityQueue maxHeap;
PriorityQueue minHeap;
public MedianFinder() {
maxHeap= new PriorityQueue<Integer>((a,b)->b-a);
minHeap= new PriorityQueue<Integer>();
}
public void addNum(int num) {
//Pushing
if ( maxHeap.isEmpty() || ((int)maxHeap.pee... | class MedianFinder {
public:
/* Implemented @StefanPochmann's Incridible Idea */
priority_queue<long long> small, large;
MedianFinder() {
}
void addNum(int num) {
small.push(num); // cool three step trick
large.push(-small.top());
small.pop();
w... | var MedianFinder = function() {
this.left = new MaxPriorityQueue();
this.right = new MinPriorityQueue();
};
/**
* @param {number} num
* @return {void}
*/
MedianFinder.prototype.addNum = function(num) {
let { right, left } = this
if (right.size() > 0 && num > right.front().element) {
right.enqueue(num)
... | Find Median from Data Stream |
Given a date string in the form Day Month Year, where:
Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
Year is in the range [1900, 2100].
Convert the date string to t... | class Solution:
def reformatDate(self, date: str) -> str:
m_dict_={"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"}
day=date[:-11]
if len(day)==1:
day="0"+day
return(date[-4... | class Solution {
public String reformatDate(String date) {
int len = date.length();
String[] monthArray = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
String year = date.substring(len - 4);
int month = Arrays.asList(monthArra... | class Solution {
public:
string reformatDate(string date) {
map<string,int>m;
m["Jan"] =1;
m["Feb"] =2;
m["Mar"] =3;
m["Apr"] =4;
m["May"] =5;
m["Jun"] =6;
m["Jul"] =7;
m["Aug"] =8;
m["Sep"] =9;
m["Oct"] =10;
m["Nov"] =1... | var reformatDate = function(date) {
const ans = [];
const month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const [inputDate,inputMonth,inputYear] = date.split(' ');
ans.push(inputYear);
ans.push("-");
const monthInd... | Reformat Date |
Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi) and radius ri of the ith circle drawn on a grid, return the number of lattice points that are present inside at least one circle.
Note:
A lattice point is a point with integer coordinates.
Points that lie on the circumf... | class Solution:
def countLatticePoints(self, c: List[List[int]]) -> int:
ans,m=0,[0]*40401
c=set(((x,y,r) for x,y,r in c))
for x, y, r in c:
for i in range(x-r, x+r+1):
d=int(sqrt(r*r-(x-i)*(x-i)))
m[i*201+y-d:i*201+y+d+1]=[1]*(d+d+1)
retur... | class Solution {
public int countLatticePoints(int[][] circles) {
Set<String> answer = new HashSet<String>();
for (int[] c : circles) {
int x = c[0], y = c[1], r = c[2];
// traversing over all the points that lie inside the smallest square capable of con... | class Solution {
public:
bool circle(int x , int y , int c1 , int c2, int r){
if((x-c1)*(x-c1) + (y-c2)*(y-c2) <= r*r)
return true ;
return false ;
}
int countLatticePoints(vector<vector<int>>& circles) {
int n = circles.size() , ans = 0 ;
set<pair<int,int>>... | var countLatticePoints = function(circles) {
let minX=minY=Infinity, maxX=maxY=-Infinity;
for(let i=0; i<circles.length; i++){
minX=Math.min(minX, circles[i][0]-circles[i][2]); maxX=Math.max(maxX, circles[i][0]+circles[i][2]);
minY=Math.min(minY, circles[i][1]-circles[i][2]); maxY=Math.max(maxY,... | Count Lattice Points Inside a Circle |
We distribute some number of candies, to a row of n = num_people people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person.
Then, we go back to the start of the row, giving n + 1 candies to the f... | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
candy_dict = {}
for i in range(num_people) :
candy_dict[i] = 0
candy, i, totalCandy = 1, 0, 0
while totalCandy < candies :
if i >= num_people :
... | class Solution {
public int[] distributeCandies(int candies, int num_people) {
int n=num_people;
int a[]=new int[n];
int k=1;
while(candies>0){
for(int i=0;i<n;i++){
if(candies>=k){
a[i]+=k;
candies-=k;
... | class Solution {
public:
vector<int> distributeCandies(int candies, int num_people) {
vector<int> Candies (num_people, 0);
int X = 0;
while (candies)
{
for (int i = 0; i < num_people; ++i)
{
int Num = X * num_people + i + 1;
if ... | var distributeCandies = function(candies, num_people) {
let i = 1, j=0;
const result = new Array(num_people).fill(0);
while(candies >0){
result[j] += i;
candies -= i;
if(candies < 0){
result[j] += candies;
break;
}
j++;
if(j === num_pe... | Distribute Candies to People |
You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.
In the ith operation (1-indexed), you will:
Choose two elements, x and y.
Receive a score of i * gcd(x, y).
Remove x and y from nums.
Return the maximum score you can receive after performing n operatio... | from functools import lru_cache
class Solution:
def maxScore(self, nums: List[int]) -> int:
def gcd(a, b):
while a:
a, b = b%a, a
return b
halfplus = len(nums)//2 + 1
@lru_cache(None)
def dfs(mask, k):
if k == halfplus:
... | class Solution {
public int maxScore(int[] nums) {
int n = nums.length;
Map<Integer, Integer> gcdVal = new HashMap<>();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
gcdVal.put((1 << i) + (1 << j), gcd(nums[i], nums[j]));
}
}
... | int dp[16384];
int gcd_table[14][14];
class Solution {
public:
int maxScore(vector<int>& nums) {
memset(dp, -1, sizeof(dp));
int sz = nums.size();
// Build the GCD table
for (int i = 0; i < sz; ++i) {
for (int j = i+1; j < sz; ++j) {gcd_table[i][j] = gcd(nums[i], nums[... | var maxScore = function(nums) {
function gcd(a, b) {
if(!b) return a;
return gcd(b, a % b);
}
const memo = new Map();
function recurse(arr, num1, op) {
if(!arr.length) return 0;
const key = arr.join() + num1;
if(memo.has(key)) return memo.g... | Maximize Score After N Operations |
You are given a non-negative integer array nums. In one operation, you must:
Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
Subtract x from every positive element in nums.
Return the minimum number of operations to make every element in nums equal to 0.
&n... | class Solution:
def minimumOperations(self, nums: List[int]) -> int:
return len(set(nums) - {0}) | class Solution {
public int minimumOperations(int[] nums) {
Set<Integer> s = new HashSet<>();
int result = 0;
if(nums[0] == 0 && nums.length == 1){
return 0;
}
else{
for (int num : nums) {
s.add(num);
}
for (int num : nums) {
... | class Solution {
public:
int minimumOperations(vector<int>& nums) {
priority_queue <int, vector<int>, greater<int> > pq;
for(int i=0;i<nums.size();i++)
pq.push(nums[i]);
int curr_min=0;
int count=0;
while(!pq.empty()){
if(pq.... | var minimumOperations = function(nums) {
let k = new Set(nums) // convert array to set; [...nums] is destructuring syntax
return k.has(0) ? k.size-1 : k.size; // we dont need 0, hence if zero exists return size-1
}; | Make Array Zero by Subtracting Equal Amounts |
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: ... | class Solution:
def multiply(self, num1: str, num2: str) -> str:
def convertToInt(numStr):
currNum = 0
N = len(numStr)
for i in range(N - 1, -1, -1):
digit = ord(numStr[i]) - ord('0')
currNum += pow(10, N-i-1) * digit
... | class Solution {
public String multiply(String num1, String num2) {
if(num1.equals("0") || num2.equals("0"))
return "0";
int[] arr=new int[num1.length()+num2.length()];
int index=0;
for(int i=num1.length()-1;i>=0;i--)
{
int carry=0;
int co... | class Solution {
void compute(string &num, int dig, int ind, string &ans){
int c = 0; // carry digit..
int i = num.size()-1;
// again travarsing the string in reverse
while(i >= 0){
int mul = dig*(num[i]-'0') + c; // the curr digit's multiplication
c = mul/... | var multiply = function(num1, num2) {
const m = num1.length;
const n = num2.length;
const steps = [];
let carry = 0;
for(let i = m - 1; i >= 0; i -= 1) {
const digitOne = parseInt(num1[i]);
let step = "0".repeat(m - 1 - i);
carry = 0;
for(let j = n - 1; j >= 0; j -=... | Multiply Strings |
You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.
The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the dista... | class Solution:
"""
Approach:
O(n^2) is very straight forward
For all the possible pairs
for i in range(n)
for j in range(i+1, n)
value[i] = max(value[i], value[i] + value[j] + i - j`)
we can do this problem in O(n) as well
values = [8, 1, 5, 2, 6]
max_val = [0, 0, 0... | class Solution {
public int maxScoreSightseeingPair(int[] values) {
int n=values.length;
int[] dp=new int[n];
dp[0]=values[0];
int ans=0;
for(int i=1;i<n;i++){
dp[i]=Math.max(dp[i-1],values[i]+i);
ans=Math.max(ans,dp[i-1]+values[i]-i);
}
... | class Solution {
public:
int maxScoreSightseeingPair(vector<int>& values) {
int ans=-1e9;
int maxSum=values[0];
int n=values.size();
for(int i=1;i<n;i++){
ans=max(ans,maxSum+values[i]-i);
maxSum=max(maxSum,values[i]+i);
}
return ans;
}
}; | /**
* @param {number[]} values
* @return {number}
*/
var maxScoreSightseeingPair = function(values) {
let n=values.length,
prevIndexMaxAddition=values[n-1],
maxValue=-2;
for(let i=n-2;i>-1;i--){
let curIndexMaxAddition=Math.max(values[i],prevIndexMaxAddition-1);
let curIndexMa... | Best Sightseeing Pair |
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap i... | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if (rec2[1]>=rec1[3] or rec2[0]>=rec1[2] or rec2[3]<=rec1[1] or rec1[0]>=rec2[2]) :
return False
else:
return True | // Rectangle Overlap
// https://leetcode.com/problems/rectangle-overlap/
class Solution {
public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
int x1 = rec1[0];
int y1 = rec1[1];
int x2 = rec1[2];
int y2 = rec1[3];
int x3 = rec2[0];
int y3 = rec2[1];
i... | class Solution {
public:
bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
int ax1 = rec1[0];
int ay1 = rec1[1];
int ax2 = rec1[2];
int ay2 = rec1[3];
int bx1 = rec2[0];
int by1 = rec2[1];
int bx2 = rec2[2];
int by2 = rec2[3];
... | /**
* @param {number[]} rec1
* @param {number[]} rec2
* @return {boolean}
*/
var isRectangleOverlap = function(rec1, rec2) {
if(rec1[0] >= rec2[2] || rec2[0] >= rec1[2] || rec1[1] >= rec2[3] || rec2[1] >= rec1[3]){
return false
}
return true
}; | Rectangle Overlap |
You are given a string s that consists of only digits.
Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.
For example, the string s = "00900... | class Solution:
def splitString(self, s: str, last_val: int = None) -> bool:
# Base case, remaining string is a valid solution
if last_val and int(s) == last_val - 1:
return True
# Iterate through increasingly larger slices of s
for i in range(1, len(s)):
cur... | class Solution {
public boolean splitString(String s) {
return isRemainingValid(s, null);
}
private boolean isRemainingValid(String s, Long previous) {
long current =0;
for(int i=0;i<s.length();i++) {
current = current * 10 + s.charAt(i)-'0';
if(current >= 100... | class Solution {
bool helper(string s, long long int tar) {
if (stoull(s) == tar) return true;
for (int i = 1; i < s.size(); ++i) {
if (stoull(s.substr(0, i)) != tar) continue;
if (helper(s.substr(i, s.size()-i), tar-1))
return true;
}
retur... | /**
* @param {string} s
* @return {boolean}
*/
var splitString = function(s) {
const backtracking = (index, prevStringValue) => {
if(index === s.length) {
return true;
}
for(let i = index; i < s.length; i++) {
const currStringValue = s.slice(index ,i + 1);
... | Splitting a String Into Descending Consecutive Values |
Given a 2D integer array matrix, return the transpose of matrix.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: matrix = [[1,2,3... | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
rows=len(matrix)
cols=len(matrix[0])
ans=[[0]*rows]*cols
for i in range(cols):
for j in range(rows):
ans[i][j]=matrix[j][i]
return ans | class Solution {
public int[][] transpose(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] trans = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
trans[i][j] = matrix[j][i];
}
}
... | class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
vector<vector<int>>result;
map<int,vector<int>>m;
for(int i=0;i<matrix.size();i++){
vector<int>v = matrix[i];
for(int j=0;j<v.size();j++){
m[j].push... | var transpose = function(matrix){
let result = []
for(let i=0;i<matrix[0].length;i++){
let col = []
for(let j= 0;j<matrix.length;j++){
col.push(matrix[j][i])
}
result.push(col)
}
return result
};
console.log(transpose( [ [1 , 2 , 3] , [ 4 , 5 , 6 ] , [ ... | Transpose Matrix |
Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.
It is guaranteed that the node to be deleted is not a tail node in the list.
Example 1:
Input: head = [4,5,1,9], node = 5
Output... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.... | class Solution {
public void deleteNode(ListNode node) {
// 4 5 1 9 : Node = 5
node.val = node.next.val;
//Copy next node val to current node.
//4 1 1 9
// ------------
//Point node.next = node.next.next
// 4 -----> 1 ----> 9
node.next = node.next... | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
int temp = node->val;
node->val = node->next->val;
node->next->val = temp;... | var deleteNode = function(node) {
let nextNode = node.next;
node.val = nextNode.val;
node.next = nextNode.next;
}; | Delete Node in a Linked List |
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, ... | """
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
node = head
while node:... | class Solution {
public Node flatten(Node head) {
Node curr = head ; // for traversal
Node tail = head; // for keeping the track of previous node
Stack<Node> stack = new Stack<>(); // for storing the reference of next node when child node encounters
while(curr != null){
i... | class Solution {
public:
Node* flatten(Node* head)
{
if(head==NULL) return head;
Node *temp=head;
stack<Node*> stk;
while(temp->next!=NULL || temp->child!=NULL || stk.size()!=0)
{
if(temp->next==NULL && temp->child==NULL && stk.size())
{
... | var flatten = function(head) {
var arr = [];
var temp = head;
var prev= null;
while(temp)
{
if(temp.child!= null)
{
arr.push(temp.next);
temp.next = temp.child;
temp.child.prev = temp;
tem... | Flatten a Multilevel Doubly Linked List |
Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
Example 1:
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the onl... | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
min_, max_ = 0, 0
min_temp = []
max_temp = []
m = len(matrix)
n = len(matrix[0])
for i in matrix:
min_temp.append(min(i))
print(min_temp)
if n >= m:
... | class Solution {
public List<Integer> luckyNumbers (int[][] matrix) {
List<Integer> luckyNums = new ArrayList();
int n = matrix.length;
int m = matrix[0].length;
for(int[] row : matrix){
int min = row[0];
int index = 0;
boolean lucky = tru... | class Solution {
public:
vector<int> luckyNumbers (vector<vector<int>>& matrix) {
unordered_map<int,vector<int>>m;
for(int i=0;i<matrix.size();i++){
vector<int>temp = matrix[i];
for(int j=0;j<temp.size();j++){
m[j].push_back(temp[j]);
}
}... | /**
* @param {number[][]} matrix
* @return {number[]}
*/
var luckyNumbers = function(matrix) {
let rowLucky = new Set();
let colLucky = new Set();
let cols = [...Array(matrix[0].length)].map(e => []);
for (let i = 0; i < matrix.length; i++) {
let row = matrix[i];
rowLucky.add(Math.mi... | Lucky Numbers in a Matrix |
You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:
It is directly connected to the top of the grid, or
At least one other brick in its four adjacent cells is stable.
You are also given an array hits, which is a sequence of erasures we want to... | from collections import defaultdict
class Solution:
def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:
parent = defaultdict()
sz = defaultdict(lambda:1)
empty = set()
def find(i):
if parent[i] != i:
parent[i] = find(parent[i])... | class Solution {
int[][] dirs = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
public int[] hitBricks(int[][] grid, int[][] hits) {
//marking all the hits that has a brick with -1
for(int i=0;i<hits.length;i++)
if(grid[hits[i][0]][hits[i][1]] == 1)
grid[hits[i][0]][hits[i][... | class Solution {
public:
// Helper function to determine if the passed node is connected to the top of the matrix
bool isConnected(vector<vector<bool>>& vis, int& i, int& j){
if(i==0)
return true;
if(i>0 && vis[i-1][j])
return true;
if(j>0 && vis[i][j-1])
... | var hitBricks = function(grid, hits) {
let output = []
for (let i = 0; i < hits.length; i++) {
let map = {};
if (grid[hits[i][0]][hits[i][1]] == 1) {
grid[hits[i][0]][hits[i][1]] = 0;
for (let j = 0; j<grid[0].length; j++) ... | Bricks Falling When Hit |
Given a string queryIP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type.
A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leading zeros. For example, "192.168.1.1" and "192.168.1... | class Solution:
def validIPAddress(self, queryIP: str) -> str:
queryIP = queryIP.replace(".",":")
ct = 0
for i in queryIP.split(":"):
if i != "":
ct += 1
if ct == 4:
for i in queryIP.split(":"):
if i == "":
r... | class Solution {
public String validIPAddress(String queryIP) {
String regexIpv4 = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
String regexIpv6 = "((([0-9a-fA-F]){1,4})\\:){7}(([0-9a-fA-F]){1,4})";
if(query... | class Solution {
public:
bool checkforIPv6(string IP){
int n = IP.size();
vector<string>store;
string s = "";
for(int i=0; i<n; i++){
if(IP[i] == ':'){
store.push_back(s);
s = "";
}
else{
s+=IP[i];
... | var validIPAddress = function(queryIP) {
const iPv4 = () => {
const address = queryIP.split('.');
if (address.length !== 4) return null;
for (const str of address) {
const ip = parseInt(str);
if (ip < 0 || ip > 255) return null;
if (ip.toString() !== str)... | Validate IP Address |
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment or decrement an element of the array by 1.
Test cases are designed so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [1,2,3]
Output: 2
Ex... | class Solution:
def minMoves2(self, nums: List[int]) -> int:
n=len(nums)
nums.sort()
if n%2==1:
median=nums[n//2]
else:
median = (nums[n//2 - 1] + nums[n//2]) // 2
ans=0
for val in nums:
ans+=abs(... | class Solution {
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int idx=(nums.length-1)/2;
int sum=0;
for(int i=0;i<nums.length;i++){
sum+=Math.abs(nums[i]-nums[idx]);
}
return sum;
}
} | class Solution {
public:
int minMoves2(vector<int>& nums) {
int result = 0, length = nums.size();
sort(nums.begin(), nums.end());
for (int i = 0; i < length; i++) {
int median = length / 2;
result += abs(nums[i] - nums[median]);
}
return result;
}
... | var minMoves2 = function(nums) {
// Sort the array low to high
nums.sort(function(a, b) { return a-b;});
let i = 0;
let j = nums.length - 1;
let res = 0;
/**
* Sum up the difference between the next highest and lowest numbers. Regardless of what number we wish to move towards, the number of... | Minimum Moves to Equal Array Elements II |
You are given the root of a binary tree.
A ZigZag path for a binary tree is defined as follow:
Choose any node in the binary tree and a direction (right or left).
If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
Change the direction from right to l... | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
self.res = 0
def helper(root):
if root is None:
return -1, -1
leftRight = helper(root.left)[1] + 1
rightLeft = helper(root.right)[0] + 1
self.res = max(self.res... | /**
* 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 {
typedef long long ll;
typedef pair<ll, ll> pi;
public:
ll ans = 0;
pi func(TreeNode* nd) {
if(!nd){
return {-1,-1};
}
pi p = { func(nd->left).second + 1, func(nd->right).first + 1 };
ans = max({ans, p.first, p.second});
return p;
}... | /** https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/
* 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)
* }
*/
/**
* ... | Longest ZigZag Path in a Binary Tree |
You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
You should rearrange the elements of nums such that the modified array follows the given conditions:
Every consecutive pair of integers have opposite signs.
For all integers with the same si... | class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
return [i for t in zip([p for p in nums if p > 0], [n for n in nums if n < 0]) for i in t] | class Solution {
public int[] rearrangeArray(int[] nums) {
int[] res = new int[nums.length];
int resIdx = 0;
int posIdx = -1;
int minusIdx = -1;
for(int i=0;i<nums.length;i++){
if(i % 2 == 0){
posIdx++;
while(nums[posIdx] <0 )posId... | class Solution {
// Uncomment/comment the below two lines for logs
// #define ENABLE_LOG(...) __VA_ARGS__
#define ENABLE_LOG(...)
public:
vector<int> rearrangeArray(vector<int>& nums) {
const int chunk_size = (int)(sqrt(nums.size())) / 2 * 2 + 2; // make it always an even number
const int original_... | var rearrangeArray = function(nums) {
let result = Array(nums.length).fill(0);
let posIdx = 0, negIdx = 1;
for(let i=0;i<nums.length;i++) {
if(nums[i]>0) {
result[posIdx] = nums[i]
posIdx +=2;
} else {
result[negIdx] = nums[i]
negIdx +=2;
}
... | Rearrange Array Elements by Sign |
Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.
Example 1:
Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: c = 3
Output: false
Constraints:
0 <= c <= 231 - 1
| import math
class Solution:
def judgeSquareSum(self, c: int) -> bool:
a = 0
while a ** 2 <= c:
b = math.sqrt(c - a ** 2)
if b.is_integer():
return True
a += 1
return False | class Solution {
public boolean judgeSquareSum(int c) {
long a = 0;
long b = (long) Math.sqrt(c);
while(a<=b){
if(((a*a) + (b*b)) == c){
return true;
}
else if((((a*a)+(b*b)) < c)){
a++;
}
else{
... | class Solution {
public:
bool judgeSquareSum(int c) {
long long start=0,end=0;
while(end*end<c){
end++;
}
long long target=c;
while(start<=end){
long long product=start*start+end*end;
if(product==target){
return true;
... | var judgeSquareSum = function(c) {
let a = 0;
let b = Math.sqrt(c) | 0;
while (a <= b) {
const sum = a ** 2 + b ** 2;
if (sum === c) return true;
sum > c ? b -= 1 : a += 1;
}
return false;
}; | Sum of Square Numbers |
On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.
A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.
Given an array stones of length n where stones[i] = [xi, yi] represents the locat... | class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
def dfs(row,col):
if seen[(row,col)]:
return 0
seen[(row,col)] = True
for r,c in tableRow[row]:
dfs(r,c)
for r,c in tableCol[col]:
dfs(r,c)
... | class Solution {
public int removeStones(int[][] stones) {
int ret=0;
DisjointSet ds=new DisjointSet(stones.length);
for(int i=0;i<stones.length;i++) {
for(int j=i+1;j<stones.length;j++) {
int s1[]=stones[i];
int s2[]=stones[j];
i... | class Solution {
class UnionFind
{
vector<int> parent, rank;
public:
int count = 0;
UnionFind(int n)
{
count = n;
parent.assign(n, 0);
rank.assign(n, 0);
for(int i=0;i<n;i++)
{
parent[i] = i;
... | /**
* @param {number[][]} stones
* @return {number}
*/
var removeStones = function(stones) {
const n = stones.length
// initial number of components(a.k.a island)
let numComponents = n
//initial forest for union find
let forest = new Array(n).fill(0).map((ele, index) => index)
// r... | Most Stones Removed with Same Row or Column |
There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.
A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true:
age[y] <= 0.5 * age[x] + 7
age[y] > age[x]
age[y] > 100 && ag... | class Solution:
"""
approach:
we can try solving this problem by finding the valid age group for each age
sort the array in descending order
iterate from right to left
for current age, find the valid agegroup to which the current age person will send a request
we can use binary search for th... | class Solution {
static int upperBound(int arr[], int target) {
int l = 0, h = arr.length - 1;
for (; l <= h;) {
int mid = (l + h) >> 1;
if (arr[mid] <= target)
l = mid + 1;
else
h = mid - 1;
}
return l;
}
pu... | class Solution {
public:
int numFriendRequests(vector<int>& ages) {
sort(ages.begin(), ages.end());
int sum = 0;
for (int i=ages.size()-1; i>=0; i--) {
int cutoff = 0.5f * ages[i] + 7;
int j = upper_bound(ages.begin(), ages.end(), cutoff) - ages.begin();
i... | var numFriendRequests = function(ages) {
const count = new Array(121).fill(0);
ages.forEach((age) => count[age]++);
let res = 0; // total friend request sent
let tot = 0; // cumulative count of people so far
for (let i = 0; i <= 120; i++) {
if (i > 14 && count[i] != 0) {
cons... | Friends Of Appropriate Ages |
In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie ag... | #["ABC","ACB","ABC","ACB","ACB"]
#d = {
# "A": [5, 0, 0],
# "B": [0, 2, 3],
# "C": [0, 3, 2]
#}
#keys represent the candidates
#index of array in dict represent the rank
#value of array item represent number of votes casted
#ref: https://www.programiz.com/python-programming/methods/built-in/sorted
class Soluti... | class Solution {
public String rankTeams(String[] votes) {
int n = votes.length;
int teams = votes[0].length();
Map<Character, int[]> map = new HashMap<>();
List<Character> chars = new ArrayList<>();
for(int i = 0 ; i < teams ; i++) {
char team = votes[0].charAt(... | class Solution {
public:
static bool cmp(vector<int>a, vector<int>b){
for(int i = 1; i<a.size(); i++){
if(a[i]!=b[i]){
return a[i]>b[i];
}
}
return a[0]<b[0];
}
string rankTeams(vector<string>& votes) {
int noofteams = votes[0].siz... | var rankTeams = function(votes) {
if(votes.length == 1)
return votes[0];
let map = new Map()
for(let vote of votes){
for(let i = 0; i < vote.length;i++){
if(!(map.has(vote[i]))){
//create all the values set as zero
map.set(vote[i],Array(vote.length).f... | Rank Teams by Votes |
Given the root of a binary tree, flatten the tree into a "linked list":
The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
The "linked list" should be in the same order as a pre-order traversal of the bina... | #Call the right of the tree node till the node root left and right is not None
#After reaching the bottom of the tree make the root.right = prev and
#root.left = None and then prev = None
#Initially prev will point to None but this is used to point the previously visited root node
#Prev pointer helps us to change the v... | class Solution {
public void flatten(TreeNode root) {
TreeNode curr=root;
while(curr!=null)
{
if(curr.left!=null)
{
TreeNode prev=curr.left;
while(prev.right!=null)
prev=prev.right;
prev.right=curr.right;... | class Solution {
public:
TreeNode* prev= NULL;
void flatten(TreeNode* root) {
if(root==NULL) return;
flatten(root->right);
flatten(root->left);
root->right=prev;
root->left= NULL;
prev=root;
}
}; | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-... | Flatten Binary Tree to Linked List |
Given a string s. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make s palindrome.
A Palindrome String is one that reads the same backward as well as forward.
Example 1:
Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is... | class Solution:
def minInsertions(self, s: str) -> int:
n = len(s)
prev_prev = [0]*n
prev = [0]*n
curr = [0] * n
for l in range(1, n):
for i in range(l, n):
if s[i] == s[i-l]:
curr[i] = prev_prev[i-1]
else:
... | class Solution {
public int minInsertions(String s) {
StringBuilder sb = new StringBuilder(s);
String str = sb.reverse().toString();
int m=s.length();
int n=str.length();
System.out.println(str);
return LCS(s,str,m,n);
}
public int LCS(String x, String y,in... | class Solution {
public:
int t[501][501];
int MinInsertion(string x,int m){
string y=x;
reverse(y.begin(),y.end());
for(int i=0;i<m+1;i++){
for(int j=0;j<m+1;j++){
if(i==0||j==0)
t[i][j]=0;
}
}
for(int i=1;i<m+1;i++){
for(int j=1;j<m+1;j++)... | var minInsertions = function(s) {
const len = s.length;
const dp = new Array(len).fill(0).map(() => {
return new Array(len).fill(-1);
});
const compute = (i = 0, j = len - 1) => {
if(i >= j) return 0;
if(dp[i][j] != -1) return dp[i][j];
if(s[i] == s[j]) return compute(... | Minimum Insertion Steps to Make a String Palindrome |
Given a sentence text (A sentence is a string of space-separated words) in the following format:
First letter is in upper case.
Each word in text are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their leng... | class Solution:
def arrangeWords(self, text: str) -> str:
l=list(text.split(" "))
l=sorted(l,key= lambda word: len(word))
l=' '.join(l)
return l.capitalize() | class Solution {
public String arrangeWords(String text) {
String[] words = text.split(" ");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].toLowerCase();
}
Arrays.sort(words, (s, t) -> s.length() - t.length());
words[0] = Character.toUpperCase(words... | class Solution {
public:
vector<pair<string,int>> words ;
string arrangeWords(string text) {
//convert to lowercase alphabet
text[0] += 32 ;
istringstream iss(text) ;
string word = "" ;
//pos is the index of each word in text.
int pos = 0 ;
... | var arrangeWords = function(text) {
let sorted = text.toLowerCase().split(' ');
sorted.sort((a, b) => a.length - b.length);
sorted[0] = sorted[0].charAt(0).toUpperCase() + sorted[0].slice(1);
return sorted.join(' ');
}; | Rearrange Words in a Sentence |
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Exam... | class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root : return 0
if root.children :
return 1 + max([self.maxDepth(x) for x in root.children])
else :
return 1 | class Solution {
public int maxDepth(Node root) {
if (root == null) return 0;
int[] max = new int[]{0};
dfs(root,1,max);
return max[0];
}
public static void dfs(Node root, int depth, int[] max) {
if (depth>max[0]) max[0] = depth;
if(root==null){
re... | class Solution {
public:
int maxDepth(Node* root)
{
if(root == NULL)
{
return 0;
}
int dep = 1, mx = INT_MIN;
helper(root, dep, mx);
return mx;
}
void helper(Node *root, int dep, int& mx)
{
if(root->children.size() == 0)
... | /**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number}
*/
var maxDepth = function(root) {
let max = 0;
if (!root) {
return max;
}
const search = (root, index) => {
max = Math.max(i... | Maximum Depth of N-ary Tree |
The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.
The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric value... | class Solution:
def getSmallestString(self, n: int, k: int) -> str:
ans = ['a']*n # Initialize the answer to be 'aaa'.. length n
val = n #Value would be length as all are 'a'
for i in range(n-1, -1, -1):
if val == k: # if value has reached k, we have created our lexicographicall... | class Solution {
public String getSmallestString(int n, int k) {
char[] ch = new char[n];
for(int i=0;i<n;i++) {
ch[i]='a';
k--;
}
int currChar=0;
while(k>0) {
currChar=Math.min(25,k);
ch[--n]+=currChar;
k-=currChar;... | class Solution {
public:
string getSmallestString(int n, int k) {
string str="";
for(int i=0;i<n;i++){
str+='a';
}
int curr=n;
int diff=k-curr;
if(diff==0) return str;
for(int i=n-1;i>=0 && diff>0;i--){
if(diff>25){
str[... | var getSmallestString = function(n, k) {
k -= n
let alpha ='_bcdefghijklmnopqrstuvwxy_',
ans = 'z'.repeat(~~(k / 25))
if (k % 25) ans = alpha[k % 25] + ans
return ans.padStart(n, 'a')
}; | Smallest String With A Given Numeric Value |
Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.
Example 1:
Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.
Example 2:
Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output: 127
Constraints... | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
TrieNode = lambda: defaultdict(TrieNode)
root = TrieNode()
for n in nums:
cur = root
for i in range(31,-1,-1):
bit = 1 if n&(1<<i) else 0
cur = cur[bit]
cur['val']=n
ans = 0
for n in nums:
cur = root
for i in ra... | class Node {
Node[] links = new Node[2];
public Node () {
}
boolean containsKey(int ind) {
return links[ind] != null;
}
Node get(int ind) {
return links[ind];
}
void put(int ind, Node node) {
links[ind] = node;
}
}
class Trie {
... | class Solution {
public:
struct TrieNode {
//trie with max 2 child, not taking any bool or 26 size value because no need
TrieNode* one;
TrieNode* zero;
};
void insert(TrieNode* root, int n) {
TrieNode* curr = root;
for (int i = 31; i >= 0; i--) {
int bit =... | var findMaximumXOR = function(nums) {
const trie = {};
const add = (num) => {
let p = trie;
for(let i = 31; i >= 0; i--) {
const isSet = (num >> i) & 1;
if(!p[isSet]) p[isSet] = {};
p = p[isSet];
}
}
const xor = (num) => {
let p = trie;... | Maximum XOR of Two Numbers in an Array |
A valid number can be split up into these components (in order):
A decimal number or an integer.
(Optional) An 'e' or 'E', followed by an integer.
A decimal number can be split up into these components (in order):
(Optional) A sign character (either '+' or '-').
One of the following formats:
One or more d... | class Solution:
def isNumber(self, s: str) -> bool:
if s == "inf" or s == "-inf" or s == "+inf" or s == "Infinity" or s == "-Infinity" or s == "+Infinity":
return False
try:
float(s)
except (Exception):
return False
return True | class Solution {
public boolean isNumber(String s) {
try{
int l=s.length();
if(s.equals("Infinity")||s.equals("-Infinity")||s.equals("+Infinity")||s.charAt(l-1)=='f'||s.charAt(l-1)=='d'||s.charAt(l-1)=='D'||s.charAt(l-1)=='F')
return false;
double x=Double.par... | /*
Max Possible combination of characters in the string has followig parts(stages) :
+/- number . number e/E +/- number
stages: 0 1 2 3 4 5 6 7
Now check each characters at there correct stages or not and increament the stage
as per the character found at ith position.
*/
class Solution {
public:
boo... | /**
* @param {string} s
* @return {boolean}
*/
var isNumber = function(s) {
const n = s.length;
const CHAR_CODE_UPPER_E = 'E'.charCodeAt(0);
const CHAR_CODE_LOWER_E = 'e'.charCodeAt(0);
const CHAR_CODE_UPPER_A = 'A'.charCodeAt(0);
const CHAR_CODE_UPPER_Z = 'Z'.charCodeAt(0);
const CHAR_CODE_L... | Valid Number |
You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the array after sorting it.
Example 1:
Input: arr... | class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
binary = []
final = []
arr.sort()
for i in arr:
binary.append(bin(i).count("1"))
for i,j in zip(arr,binary):
final.append((i,j))
z = sorted(final, key=lambda x:x[1])
... | class Solution {
public int[] sortByBits(int[] arr) {
Integer[] arrInt = new Integer[arr.length];
for(int i=0;i<arr.length;i++) {
arrInt[i]=arr[i];
}
Arrays.sort(arrInt, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer... | class Solution {
public:
vector<int> sortByBits(vector<int>& arr) {
int n = size(arr);
priority_queue<pair<int, int>> pq;
for(auto &x : arr) {
int count = 0;
int a = x;
while(a) {
count += a & 1;
a >>= 1;
... | var sortByBits = function(arr) {
const map = {};
for (let n of arr) {
let counter = 0, item = n;
while (item > 0) {
counter += (item & 1); //increment counter if the lowest (i.e. the rightest) bit is 1
item = (item >> 1); //bitwise right shift (here is equivalent to... | Sort Integers by The Number of 1 Bits |
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
Example 1:
Input: s = "aba"
Output: true
Example 2:
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc"
Output: false
Constraints:
1 &... | class Solution:
def validPalindrome(self, s: str) -> bool:
has_deleted = False
def compare(s, has_deleted):
if len(s) <= 1:
return True
if s[0] == s[-1]:
return compare(s[1:-1], has_deleted)
else:
if not has_delet... | class Solution {
boolean first = false;
public boolean validPalindrome(String s) {
int left = 0;
int right = s.length()-1;
while(left <= right){
if( s.charAt(left) == (s.charAt(right))){
left++;
right--;
}else if(!... | class Solution {
int first_diff(string s) {
for (int i = 0; i < (s.size() + 1) / 2; ++i) {
if (s[i] != s[s.size() - 1 - i]) {
return i;
}
}
return -1;
}
public:
bool validPalindrome(string s) {
int diff = first_diff(s);
if (diff == -1 || (s.size() % 2 == 0 && diff + 1... | /*
Solution:
1. Use two pointers, one initialised to 0 and the other initialised to end of string. Check if characters at each index
are the same. If they are the same, shrink both pointers. Else, we have two possibilities: one that neglects character
at left pointer and the other that neglects character at right poin... | Valid Palindrome II |
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 its... | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummyHead = ListNode(0)
tail = dummyHead
carry = 0
while l1 is not None or l2 is not None or carry != 0:
digit1 = l1.val if l1 is not None else 0
digit2 = l2.val if l2 is not Non... | class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode dummy = new ListNode(-1);
ListNode temp = dummy;
int carry = 0;
while(l1 != null || l2 != null || carry != 0){
... | class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head1, *head2, *head3, *temp;
head1=l1;
head2 = l2;
head3=NULL;
int carry = 0, res = 0;
while(head1 && head2){
res = head1->val +head2->val + carry;
carry ... | /**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
var List = new ListNode(0);
var head = List;
var sum = 0;
va... | Add Two Numbers |
An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.
Given an integer n, return the smallest numerically balanced number strictly greater than n.
Example 1:
Input: n = 1
Output: 22
Explanation:
22 is numerically balanced since:
- The d... | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
n_digits = len(str(n))
next_max = {
1: [1],
2: [22],
3: [122, 333],
4: [1333, 4444],
5: [14444, 22333, 55555],
6: [122333, 224444, 666666, 155555],
... | class Solution {
public int nextBeautifulNumber(int n) {
while(true){
n++;
int num = n; //test this number
int [] freq = new int[10]; // 0 to 9
while(num > 0){ //calculate freq of each digit in the num
int rem = num % 10; //this is remainder
... | class Solution {
public:
bool valid(int n)
{
vector<int> map(10,0);
while(n)
{
int rem = n%10;
map[rem]++;
n = n/10;
}
for(int i=0; i<10; i++)
if(map[i] && map[i]!=i) return false;
return true;
}
int nex... | /**
* @param {number} n
* @return {number}
*/
var nextBeautifulNumber = function(n) {
//1224444 is next minimum balanced number after 10^6
for(let i=n+1; i<=1224444;i++){//Sequency check each number from n+1 to 1224444
if(isNumericallyBalanced(i)){
return i;//Return the number if is a bal... | Next Greater Numerically Balanced Number |
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence ... | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if len(s) > len(t):return False
if len(s) == 0:return True
subsequence=0
for i in range(0,len(t)):
if subsequence <= len(s) -1:
print(s[subsequence])
if s[subsequence]==t[i]:
... | class Solution
{
public boolean isSubsequence(String s, String t)
{
int i,x,p=-1;
if(s.length()>t.length())
return false;
for(i=0;i<s.length();i++)
{
x=t.indexOf(s.charAt(i),p+1);
if(x>p)
p=x;
else
... | class Solution {
public:
bool isSubsequence(string s, string t) {
int n = s.length(),m=t.length();
int j = 0;
// For index of s (or subsequence
// Traverse s and t, and
// compare current character
// of s with first unmatched char
// of t, if matched
// then move ahead in... | /**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isSubsequence = function(s, t) {
for (let i = 0, n = s.length; i < n; i++)
if (t.includes(s[i]))
t = t.slice(t.indexOf(s[i]) + 1);
else return false;
return true;
} | Is Subsequence |
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1's permutations is the substring of s2.
Example 1:
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input:... | class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False
s1_map = {}
s2_map = {}
for i in range(ord('a') , ord('z') + 1):
s1_map[chr(i)] = 0
s2_map[chr(i)] = 0
for i in s1:
... | class Solution {
public boolean checkInclusion(String s1, String s2) {
if(s1.length() > s2.length()) {
return false;
}
int[]s1Count = new int[26];
int[]s2Count = new int[26];
for(int i = 0; i < s1.length(); i++) {
char c = s1.charAt(i... | class Solution {
public:
bool checkInclusion(string s1, string s2) {
sort(s1.begin(),s1.end());
int n = s1.size(), m = s2.size();
for(int i=0;i<=m-n;i++)
{
string s = s2.substr(i,n);
sort(s.begin(),s.end());
if(s1 == s) return true;
}
return false;
}
}; | const getCharIdx = (c) => c.charCodeAt(0) - 'a'.charCodeAt(0);
const isEqual = (a, b) => a.every((v, i) => v == b[i]);
var checkInclusion = function(s1, s2) {
const occS1 = new Array(26).fill(0);
const occS2 = new Array(26).fill(0);
const s1Len = s1.length, s2Len = s2.length;
if(s1Len > s2Len) return... | Permutation in String |
You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.
You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.
In each move, you may take an unbrok... | class Solution:
@cache
def twoEggDrop(self, n: int) -> int:
return min((1 + max(i - 1, self.twoEggDrop(n - i)) for i in range (1, n)), default = 1) | class Solution {
public int twoEggDrop(int n) {
int egg = 2; // hard coded to 2 eggs for this problem
int[][] dp = new int[n+1][egg+1];
return eggDrop(n, egg, dp);
}
int eggDrop(int n, int egg, int[][] dp) {
if(n <= 2 || egg == 1) return n;
if(dp[n][egg] != 0) return... | int dp[1001][1001];
class Solution {
public:
int solve(int e, int f){
if(f == 0 || f == 1){
return f;
}
if(e == 1){
return f;
}
if(dp[e][f] != -1) return dp[e][f];
int mn = INT_MAX;
int left = 1, right = f;
while(left <= right){... | /** https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/
* @param {number} n
* @return {number}
*/
var twoEggDrop = function(n) {
// Writing down strategy on example 2 we can observe following pattern:
// Drop at floor: 9 22 34 45 55 64 72 79 85 90 94 97 99 100... | Egg Drop With 2 Eggs and N Floors |
It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possibl... | class Solution:
def maxIceCream(self, costs: List[int], coins: int) -> int:
costs.sort()
i= 0
for price in costs:
if price<= coins:
i+= 1
coins-= price
else:
break
return i | class Solution {
public int maxIceCream(int[] costs, int coins) {
//Greedy Approach
//a. sort cost in increasing order
Arrays.sort(costs);
int count = 0;
for(int cost : costs){
//b. check remainig coin is greater or equal than cuurent ice - cream cost
... | class Solution {
public:
int maxIceCream(vector<int>& costs, int coins) {
int n=costs.size();
sort(costs.begin(),costs.end());
int i=0;
for(;i<n && coins>=costs[i];i++){
coins-=costs[i];
}
return i;
}
}; | var maxIceCream = function(costs, coins) {
costs.sort((a, b) => a - b);
let count = 0;
for (let i = 0; i < costs.length; i++) {
if (costs[i] <= coins) {
count++;
coins -= costs[i]
} else {
break; // a small optimization, end the loop early if coins go down to zero before we reach end of... | Maximum Ice Cream Bars |
Given the root of a binary tree, return the lowest common ancestor of its deepest leaves.
Recall that:
The node of a binary tree is a leaf if and only if it has no children
The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1.
The lowest common ancestor o... | class Solution:
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.max_lvl = (0,[])
self.pathes = {}
def rec(root,parent,lvl):
if not root:
return
if lvl > self.max_lvl[0]:
self.max_lvl = (lvl,[root])
... | class Solution {
public TreeNode lcaDeepestLeaves(TreeNode root) {
if (root.left == null && root.right == null) return root;
int depth = findDepth(root);
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int count = 0;
while (!q.isEmpty()) {
int size ... | class Solution {
public:
stack<TreeNode *>st;
vector<TreeNode * >vec;
int mx = INT_MIN;
void ch(TreeNode * root, int h){
if(!root) return ;
ch(root->left, h+1);
ch(root->right, h+1);
if(h==mx){
vec.push_back(root);
}
els... | var lcaDeepestLeaves = function(root) {
if(!root) return root;
// keep track of max depth if node have both deepest node
let md = 0, ans = null;
const compute = (r = root, d = 0) => {
if(!r) {
md = Math.max(md, d);
return d;
}
const ld = compute(r.left, d... | Lowest Common Ancestor of Deepest Leaves |
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.
You are also given a... | class Solution:
def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
n = len(classes)
impacts = [0]*n
minRatioIndex = 0
# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)
for i in range(n):
passCount = classes[i][0]... | class Solution {
public double maxAverageRatio(int[][] classes, int extraStudents) {
PriorityQueue<double[]> pq = new PriorityQueue<>(new Comparator<double[]>(){
public int compare(double[] a, double[] b){
double adiff = (a[0]+1)/(a[1]+1) - (a[0]/a[1]);
double bdi... | struct cmp{
bool operator()(pair<int,int> a, pair<int,int> b){
double ad = (a.first+1)/(double)(a.second+1) - (a.first)/(double)a.second;
double bd = (b.first+1)/(double)(b.second+1) - (b.first)/(double)b.second;
return ad < bd;
}
};
class Solution {
public:
double maxAverageRatio(v... | /**
* @param {number[][]} classes
* @param {number} extraStudents
* @return {number}
*/
class MaxHeap {
constructor() {
this.heap = [];
}
push(value) {
this.heap.push(value);
this.heapifyUp(this.heap.length - 1);
}
pop() {
if (this.heap.length === 0) {
... | Maximum Average Pass Ratio |
You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.
In a tiling, every square must be covered by a tile. Two tilings are different if and ... | class Solution(object):
def numTilings(self, n):
dp = [1, 2, 5] + [0] * n
for i in range(3, n):
dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007
return dp[n - 1] | class Solution {
public int numTilings(int n) {
long[] dp = new long[n + 3]; dp[0] = 1; dp[1] = 2; dp[2] = 5;
for (int i = 3; i < n; i ++) {
dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007;
}
return (int)dp[n - 1];
}
} | class Solution {
public:
int numTilings(int n) {
long dp[n+1];
dp[0]=1;
for(int i=1; i<=n; i++){
if(i<3)
dp[i]=i;
else
dp[i] = (dp[i-1]*2+dp[i-3])%1000000007;
}
return (int)dp[n];
}
}; | var numTilings = function(n) {
let mod = 10 ** 9 + 7;
let len = 4;
let ways = new Array(len).fill(0);
// base cases
ways[0] = 1;
ways[1] = 1;
ways[2] = 2;
// already calculated above
if (n < len - 1) {
return ways[n];
}
// use % len to circulate values inside our a... | Domino and Tromino Tiling |
You are given an integer array nums where the largest integer is unique.
Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.
Example 1:
Input: nums = [3,6,1,0]
Output: 1
Expl... | class Solution:
def dominantIndex(self, nums: List[int]) -> int:
if len(nums) is 1:
return 0
dom = max(nums)
i = nums.index(dom)
nums.remove(dom)
if max(nums) * 2 <= dom:
return i
return -1 | class Solution {
public int dominantIndex(int[] nums) {
if(nums == null || nums.length == 0){
return -1;
}
if(nums.length == 1){
return 0;
}
int max = Integer.MIN_VALUE + 1;
int secondMax = Integer.MIN_VALUE;
int index = 0;
... | class Solution {
public:
int dominantIndex(vector<int>& nums) {
if(nums.size() < 2){
return nums.size()-1;
}
int max1 = INT_MIN;
int max2 = INT_MIN;
int result = -1;
for(int i=0;i<nums.size();i++){
if(nums[i] > max1){
result = i... | /**
* @param {number[]} nums
* @return {number}
*/
var dominantIndex = function(nums) {
let first = -Infinity;
let second = -Infinity;
let ans = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] > first) {
second = first;
first = nums[i];
ans = i;
} else if (nums[i] > second) {... | Largest Number At Least Twice of Others |
Given a string s consisting of lowercase English letters, return the first letter to appear twice.
Note:
A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.
s will contain at least one letter that appears twice.
Example 1:
Input: s = "abccb... | class Solution:
def repeatedCharacter(self, s: str) -> str:
occurences = defaultdict(int)
for char in s:
occurences[char] += 1
if occurences[char] == 2:
return char | class Solution {
public char repeatedCharacter(String s) {
HashSet<Character> hset = new HashSet<>();
for(char ch:s.toCharArray())
{
if(hset.contains(ch))
return ch;
else
hset.add(ch);
}
return ' ';
}
} | class Solution
{
public:
char repeatedCharacter(string s)
{
unordered_map<char, int> mp; //for storing occurrences of char
char ans;
for(auto it:s)
{
if(mp.find(it) != mp.end()) //any char which comes twice first will be the ans;
{
ans = i... | var repeatedCharacter = function(s) {
const m = {};
for(let i of s) {
if(i in m) {
m[i]++
} else {
m[i] = 1
}
if(m[i] == 2) {
return i
}
}
}; | First Letter to Appear Twice |
Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.
Return True if t... | class Solution:
def isGoodArray(self, nums: List[int]) -> bool:
def gcd(a,b):
while a:
a, b = b%a, a
return b
return reduce(gcd,nums)==1 | class Solution {
public boolean isGoodArray(int[] nums) {
int gcd = nums[0];
for(int i =1; i<nums.length; i++){
gcd = GCD(gcd, nums[i]);
if (gcd==1)
return true;
}
return gcd ==1;
}
int GCD(int a, int b){
if(b==0){
... | class Solution {
public:
bool isGoodArray(vector<int>& nums) {
int gcd=0;
for(int i=0; i<nums.size(); i++){
gcd=__gcd(gcd,nums[i]);
}return gcd==1;
}
}; | var isGoodArray = function(nums) {
let gcd = nums[0]
for(let n of nums){while(n){[gcd, n] = [n, gcd % n]}}
return (gcd === 1)
}; | Check If It Is a Good Array |
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 3
Outp... | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
memo ={}
memo[1] = 1
memo[2] = 2
def climb(n):
if n in memo: # if the recurssion already done before first take a look-up in the look-up table
... | class Solution {
public int climbStairs(int n) {
int[] memo = new int[n + 1];
return calculateWays(n, memo);
}
private int calculateWays(int n, int[] memo) {
if (n == 1 || n == 2) {
return n;
}
if (memo[n] != 0) {
return memo[n];
... | class Solution {
public:
int climbStairs(int n) {
if (n <= 2) return n;
int prev = 2, prev2 = 1, res;
for (int i = 3; i <= n; i++) {
res = prev + prev2;
prev2 = prev;
prev = res;
}
return res;
}
}; | /*
DP
dp[i] represents the total number of different ways to take i steps
So, we want to get dp[n].
dp[n] = dp[n-1] + dp[n-2] because we can either take 1 or 2 steps.
We have two base cases: dp[1] = 1 and dp[2] = 2 because
there is one way to take 1 step and there are two ways to take 2 steps (1 step + 1 step OR 2 st... | Climbing Stairs |
You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.
You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an o... | class Solution:
def pathsWithMaxScore(self, board: List[str]) -> List[int]:
## Basic information: height and width of board
h, w = len(board), len(board[0])
# ----------------------------------------------------------------------------
# Use pathon native cahce as memoization for ... | class Solution {
public int[] pathsWithMaxScore(List<String> board) {
int M = (int)1e9+7;
int m = board.size();
int n = board.get(0).length();
int[][] dp = new int[m][n];
int[][] ways = new int[m][n];
ways[0][0]=1; // base case.
int[][] dirs = {{-1, 0}, {0, -1... | class Solution {
public:
int mod=1e9+7;
map<pair<int,int>,pair<int,int>>h;
pair<int,int>solve(vector<string>&board,int i,int j,int n,int m)
{
//base case if you reach top left then 1 path hence return 1
if(i==0 && j==0)return {0,1};
//return 0 as no path is detected
if(i<... | var pathsWithMaxScore = function(board) {
let n = board.length, dp = Array(n + 1).fill(0).map(() => Array(n + 1).fill(0).map(() => [-Infinity, 0]));
let mod = 10 ** 9 + 7;
dp[n - 1][n - 1] = [0, 1]; // [max score, number of paths]
for (let i = n - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
... | Number of Paths with Max Score |
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
Given two nodes start and&n... | class Solution(object):
def maxProbability(self, n, edges, succProb, start, end):
adj=[[] for i in range(n)]
dist=[sys.maxsize for i in range(n)]
heap=[]
c=0
for i,j in edges:
adj[i].append([j,succProb[c]])
adj[j].append([i,succProb[c]])
c+... | class Pair{
int to;
double prob;
public Pair(int to,double prob){
this.to=to;
this.prob=prob;
}
}
class Solution {
public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {
List<List<Pair>> adj=new ArrayList<>();
for(int i=0;i<n;i++){... | class Solution {
public:
double maxProbability(int n, vector<vector<int>>& edges, vector<double>& succProb, int start, int end) {
vector<vector<pair<int, double>>> graph(n);
for(int i = 0; i < edges.size(); ++i){
graph[edges[i][0]].push_back({edges[i][1], succProb[i]});
graph... | var maxProbability = function(n, edges, succProb, start, end) {
const graph = new Map();
edges.forEach(([a, b], i) => {
const aSet = graph.get(a) || [];
const bSet = graph.get(b) || [];
aSet.push([b, succProb[i]]), bSet.push([a, succProb[i]]);
graph.set(a, aSet), graph.set(b, bSe... | Path with Maximum Probability |
Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.
Example 1:
Input: nums = [1,4,3,2]
Output: 4
Explanation: All possible pairings (ignoring the ordering of elements) ... | class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
summ = 0
for i in range(0,len(nums),2):
summ += min(nums[i],nums[i+1])
return summ | class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int sum = 0;
for(int i = 0; i < nums.length; i+=2){
sum += nums[i];
}
return sum;
}
} | class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int res=0;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i+=2){
res+=min(nums[i],nums[i+1]);
}
return res;
}
}; | var arrayPairSum = function(nums) {
nums.sort((a, b) => a - b);
let total = 0;
for (let i = 0; i < nums.length; i += 2) {
total += Math.min(nums[i], nums[i + 1]);
}
return total;
}; | Array Partition |
Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
... | class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 1:
return [[1]]
if numRows == 2:
return [[1], [1, 1]]
ans = [[1], [1, 1]]
for x in range(1, numRows - 1):
tmp = [1]
for k in range(len(ans[x]) - 1):
... | class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new LinkedList();
list.add(Arrays.asList(1));
if(numRows == 1) return list;
list.add(Arrays.asList(1,1));
for(int i = 1; i < numRows - 1; i++) {
List<Integer> t... | class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ans(numRows, vector<int>());
for(int i = 0; i<numRows; i++){
for(int j = 0; j <= i; j++){
if(j == 0 || j == i){
ans[i].push_back(1);
}else{
... | var generate = function(numRows) {
let ans = new Array(numRows)
for (let i = 0; i < numRows; i++) {
let row = new Uint32Array(i+1).fill(1),
mid = i >> 1
for (let j = 1; j <= mid; j++) {
let val = ans[i-1][j-1] + ans[i-1][j]
row[j] = val, row[row.length-j-1] = ... | Pascal's Triangle |
In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.
For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.
The twin su... | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
nums = []
curr = head
while curr:
nums.append(curr.val)
curr = curr.next
N = len(nums)
res = 0
for i in range(N // 2):
res = max(res, nums[i] + nums[N - i - 1])
... | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int pairSum(ListNode head) {
... | class Solution {
public:
ListNode* reverse(ListNode* head){
ListNode* prev=NULL,*curr=head,*nextstop;
while(curr){
nextstop=curr->next;
curr->next=prev;
prev=curr;
curr=nextstop;
}
return prev;
}
ListNode* findMiddleNode(Li... | var pairSum = function(head) {
const arr = [];
let max = 0;
while (head) {
arr.push(head.val);
head = head.next;
}
for (let i = 0; i < arr.length / 2; i++) {
const sum = arr[i] + arr[arr.length - 1 - i]
max = Math.max(max, sum);
}
return max;
}; | Maximum Twin Sum of a Linked List |
You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:
1 which means a street connecting the left cell and the right cell.
2 which means a street connecting the upper cell and the lower cell.
3 which means a street connecting the left cell and the lower cell.
4 which ... | class Solution:
def hasValidPath(self, grid: List[List[int]]) -> bool:
r,c=len(grid),len(grid[0])
dic={
2:[(-1,0),(1,0)],
1:[(0,1),(0,-1)],
5:[(-1,0),(0,-1)],
3:[(1,0),(0,-1)],
6:[(0,1),(-1,0)],
4:[(0,1),(1,0)]
... | class Solution {
public boolean hasValidPath(int[][] grid) {
int m=grid.length, n=grid[0].length;
int[][] visited=new int[m][n];
return dfs(grid, 0, 0, m, n, visited);
}
public boolean dfs(int[][] grid, int i, int j, int m, int n, int[][] visited){
if(i==m-1 && j==n-1) return... | class Solution {
public:
bool hasValidPath(vector<vector<int>>& grid)
{
int m = grid.size();
int n = grid[0].size();
if(m==1 and n==1) return true;
// 2D - direction vector for all streets
// 0th based indexing 0 to 11
// Let grid value g[i][j] = 4,... | var hasValidPath = function(grid) {
if (grid[0][0] === 5) return false;
const M = grid.length, N = grid[0].length;
const SEGMENTS = {
1: {dirs: [[0,-1], [0,1]], adjs: [[1,4,6], [1,3,5]]},
2: {dirs: [[-1,0], [1,0]], adjs: [[2,3,4], [2,5,6]]},
3: {dirs: [[0,-1], [1,0]], adjs: [[1,4,6], [2,5,6]]},
4: {dirs: [[... | Check if There is a Valid Path in a Grid |
At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction ... | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
change = {5:0,10:0}
for i in bills:
if i==5:
change[5]+=1
elif i==10:
if change[5]>0:
change[5]-=1
change[10]+=1
else:
... | class Solution {
public boolean lemonadeChange(int[] bills) {
int count5 = 0, count10 = 0;
for(int p : bills){
if(p == 5){
count5++;
}
else if(p == 10){
if(count5 > 0){
count5--;
count10++;
... | class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
unordered_map<int, int> m;
int change = 0;
for(int i = 0 ; i < bills.size(); i++)
{
m[bills[i]]++;
if(bills[i] > 5)
{
change = bills[i] - 5;
... | * @param {number[]} bills
* @return {boolean}
*/
var lemonadeChange = function(bills) {
let cashLocker = {
"5": 0,
"10": 0,
}
for (let i = 0; i < bills.length; i++) {
if (bills[i] === 5) {
cashLocker["5"] += 1;
} else if (bills[i] === 10 && cashLocker["5"] > 0) {
cashLocker["5... | Lemonade Change |
Given an array of non-negative integers nums, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
You can assume that you can always reach the last index.
&n... | class Solution(object):
def jump(self, nums):
ans = l = r = 0
while r < len(nums) - 1:
farthestJump = 0
for i in range(l, r + 1):
farthestJump = max(farthestJump, i + nums[i])
l = r + 1
r = farthestJump
ans += 1
... | class Solution {
public int jump(int[] nums) {
int result = 0;
int L = 0;
int R = 0;
while (R < nums.length - 1) {
int localMaxRight = 0;
for (int i=L; i<=R; i++) {
localMaxRight = Math.max(i + nums[i], localMaxRight);
}
... | class Solution {
public:
int jump(vector<int>& nums) {
int step=0, jump_now;
int ans = 0, index=0, i, mx;
if(nums.size()==1) return ans;
while(index+step<nums.size()-1){
ans++;
step = nums[index];
if(index+step>=nums.size()-1) break;
mx... | **//Time Complexity : O(n), Space Complexity: O(1)**
var jump = function(nums) {
var jump = 0;
var prev = 0;
var max = 0;
for (var i = 0; i < nums.length - 1; i++) {
// Keep track of the maximum jump
max = Math.max(max, i + nums[i]);
// When we get to the index where we had our... | Jump Game II |
There is a programming language with only four operations and one variable X:
++X and X++ increments the value of the variable X by 1.
--X and X-- decrements the value of the variable X by 1.
Initially, the value of X is 0.
Given an array of strings operations containing a list of operations, return the final va... | class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for o in operations:
if '+' in o:
x += 1
else:
x -= 1
return x | class Solution {
public int finalValueAfterOperations(String[] operations) {
int val = 0;
for(int i = 0; i<operations.length; i++){
if(operations[i].charAt(1)=='+') val++;
else val--;
}
return val;
}
} | class Solution {
public:
int finalValueAfterOperations(vector<string>& o,int c=0) {
for(auto &i:o) if(i=="++X" or i=="X++") c++; else c--;
return c;
}
}; | var finalValueAfterOperations = function(operations) {
let count = 0;
for(let i of operations) {
if(i === 'X++' || i === '++X') count++;
else count--;
}
return count;
}; | Final Value of Variable After Performing Operations |
You are given an integer array nums. In one move, you can choose one element of nums and change it by any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: Change the array [5,3,2,... | class Solution:
def minDifference(self, nums: List[int]) -> int:
if len(nums) <= 3:
return 0
nums.sort()
t1 = nums[-1] - nums[3]
t2 = nums[-4] - nums[0]
t3 = nums[-2] - nums[2]
t4 = nums[-3] - nums[1]
return min(t1,t2,t3,t4) | class Solution {
public int minDifference(int[] nums) {
// sort the nums
// to gain the mini difference
// we want to remove the three smallest or biggest
// 0 - 3
// 1 - 2
// 2 - 1
// 3 - 0
if(nums.length <= 4){
return 0;
}
... | class Solution {
public:
int minDifference(vector<int>& nums) {
int n =nums.size();
sort( nums.begin(), nums.end());
if( n<5){
return 0;
}
else return min({nums[n-4]- nums[0],nums[n-3]- nums[1] ,nums[n-2]-nums[2], nums[n-1]-nums[3]});
}
}; | var minDifference = function(nums) {
let len = nums.length;
if (len < 5) return 0;
nums.sort((a,b) => a-b)
return Math.min(
( nums[len-1] - nums[3] ), // 3 elements removed from start 0 from end
( nums[len-4] - nums[0] ), // 3 elements removed from end 0 from start
( nums[le... | Minimum Difference Between Largest and Smallest Value in Three Moves |
A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and:
It is the empty string, 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 ... | class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
ans = []
last = 1
for i in seq:
if i == '(':
if last == 0: ans.append(1)
else:ans.append(0)
else:
ans.append(last)
last = (last + 1) % 2
... | class Solution {
public int[] maxDepthAfterSplit(String seq) {
int[] res = new int[seq.length()];
for(int i=0; i<seq.length(); i++){
res[i] = seq.charAt(i) == '(' ? i & 1 : 1-i & 1;
}
return res;
}
} | class Solution {
public:
vector<int> maxDepthAfterSplit(string seq) {
//since we want the difference to be as low as possible so we will try to balance both A and B by trying to maintain the number of paranthesis as close as close as possible
vector<int> indexA, indexB, res(seq.length(), 0 );
... | /**
* @param {string} seq
* @return {number[]}
*/
var maxDepthAfterSplit = function(seq) {
let arr = []
for(let i=0; i<seq.length; i++){
arr.push(seq[i] == "(" ? i & 1 : 1-i & 1)
}
return arr
}; | Maximum Nesting Depth of Two Valid Parentheses Strings |
You are given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two... | class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
l, windowSum, res = 0, 0, float('inf')
min_till = [float('inf')] * len(arr) # records smallest lenth of subarry with target sum up till index i.
for r, num in enumerate(arr): # r:right pointer and index of num in ... | class Solution {
public int minSumOfLengths(int[] arr, int target) { //this fits the case when there's negative number, kind like 560
if (arr == null || arr.length == 0) return 0;
Map<Integer, Integer> map = new HashMap<>(); //sum - index
map.put(0, -1);
int sum = 0;
for (int... | class Solution {
public:
int minSumOfLengths(vector<int>& arr, int target) {
int n=arr.size();
vector<int> prefix(n,INT_MAX);
vector<int> suffix(n,INT_MAX);
int sum=0;
int start=0;
for(int end=0;end<n;end++){
sum+=arr[end];
while(sum>target){
... | var minSumOfLengths = function(arr, target) {
let left=0;
let curr=0;
let res=Math.min(); // Math.min() without any args will be Infinite
const best=new Array(arr.length).fill(Math.min());
let bestSoFar=Math.min()
for(let i=0;i<arr.length;i++){
curr+=arr[i]
while(curr>target){
... | Find Two Non-overlapping Sub-arrays Each With Target Sum |
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smal... | class DSU:
def __init__(self):
self.parentof = [-1 for _ in range(100001)]
self.rankof = [1 for _ in range(100001)]
def find(self,ele):
def recur(ele):
if self.parentof[ele]==-1:
return ele
par = recur(self.parentof[ele])
self.parento... | class Solution {
int[]parent;
int[]rank;
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
parent = new int[s.length()];
rank = new int[s.length()];
for(int i=0;i<parent.length;i++){
parent[i] = i;
rank[i] = 0;
}
... | class Solution {
public:
vector<int> parent;
int findParent(int n)
{
if(parent[n] == n) return n;
return parent[n] = findParent(parent[n]);
}
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs)
{
map<int, set<int>> mp;
parent.resize(s.size());
... | var smallestStringWithSwaps = function(s, pairs) {
const uf = new UnionFind(s.length);
pairs.forEach(([x,y]) => uf.union(x,y))
const result = [];
for (const [root, charIndex] of Object.entries(uf.disjointSets())) {
let chars = charIndex.map(i => s[i])
chars.sort();
charIndex.forEa... | Smallest String With Swaps |
Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
If the index is on the left edge of the array, then the left sum is 0 because ... | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
right = sum(nums)
left = 0
for i in range(len(nums)):
right -= nums[i]
left += nums[i - 1] if i > 0 else 0
if right == left: return i
return -1 | class Solution {
public int pivotIndex(int[] nums) {
int leftsum = 0;
int rightsum = 0;
for(int i =1; i< nums.length; i++) rightsum += nums[i];
if (leftsum == rightsum) return 0;
for(int i = 1 ; i < nums.length; i++){
leftsum += nums[i-1];
rightsum... | class Solution {
public:
int pivotIndex(vector<int>& nums) {
int sum=0, leftSum=0;
for (int& n : nums){
sum += n;
}
for(int i=0; i<nums.size();i++){
if(leftSum == sum-leftSum-nums[i]){
return i;
}
leftSum += nums[i];
... | /**
* @param {number[]} nums
* @return {number}
*/
var pivotIndex = function(nums) {
//step 1
var tot=0;
for (let i = 0; i < nums.length; i++) {
tot+= nums[i];
}
// Step 2
left = 0 ;
for (let j = 0; j < nums.length; j++) {
right = tot - nums[j] - left;
if (le... | Find Pivot Index |
You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj).
The ith rectangle has its bottom-left corner point at the coordina... | class Solution:
def binarySearch(self, arr, target):
left, right = 0, len(arr)
ans = None
while left < right:
mid = left + ((right-left)//2)
if arr[mid] >= target:
# Potential answer found! Now try to minimize it iff possible.
ans = mid... | class Solution {
public int[] countRectangles(int[][] rectangles, int[][] points) {
int max = Integer.MIN_VALUE;
TreeMap<Integer, List<Integer>> rects = new TreeMap<>();
for(int[] rect : rectangles) {
if (!rects.containsKey(rect[1])) {
rects.put(rect[1], new Arra... | class Solution {
public:
vector<int> countRectangles(vector<vector<int>>& rectangles, vector<vector<int>>& points) {
int i, count, ind, x, y, n = rectangles.size();
vector<int> ans;
vector<vector<int>> heights(101);
for(auto rect : rectangles)
h... | var countRectangles = function(rectangles, points) {
let buckets = Array(101).fill(0).map(() => []);
for (let [x, y] of rectangles) {
buckets[y].push(x);
}
for (let i = 0; i < 101; i++) buckets[i].sort((a, b) => a - b);
let res = [];
for (let point of points) {
let sum = 0;
for (let j = point[1... | Count Number of Rectangles Containing Each Point |
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Example 1:
Input: n = 3
Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Example 2:
Input: n = 1
Output: ... | # 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 generateTrees(self, n: int) -> List[Optional[TreeNode]]:
# define a sorted list of the numbers, for each num in that list ,... | /**
* 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:
vector<TreeNode*> solve(int start, int end)
{
//base case
if(start>end){
return {NULL};
}
vector<TreeNode*> lChild, rChild, res;
//forming a tree, by keeping each node as root node
for(int i=start; i<=end; i++)
{
... | var generateTrees = function(n) {
if(n <= 0){
return [];
}
return generateRec(1, n);
};
function generateRec(start, end){
let result = [];
if(start > end){
result.push(null);
return result;
}
for(let i = start; i <end+1; i++){
let left = generateRec(start,... | Unique Binary Search Trees II |
Design a number container system that can do the following:
Insert or Replace a number at the given index in the system.
Return the smallest index for the given number in the system.
Implement the NumberContainers class:
NumberContainers() Initializes the number container system.
void change(int index, int nu... | class NumberContainers:
def __init__(self):
self.numbersByIndex = {}
self.numberIndexes = defaultdict(set)
self.numberIndexesHeap = defaultdict(list)
def change(self, index: int, number: int) -> None:
if index in self.numbersByIndex:
if number != self.numbersByIndex[... | class NumberContainers {
Map<Integer,TreeSet<Integer>> map;
Map<Integer,Integer> m;
public NumberContainers() {
map=new HashMap<>();
m=new HashMap<>();
}
public void change(int index, int number) {
m.put(index,number);
if(!map.containsKey(number)) map.pu... | class NumberContainers {
public:
map<int, int> indexToNumber; // stores number corresponding to an index.
map<int, set<int>>numberToIndex; // stores all the indexes corresponding to a number.
NumberContainers() {}
void change(int index, int number) {
if (!indexToNumber.count(index)) { // if th... | var NumberContainers = function() {
this.obj = {}
this.global = {}
};
NumberContainers.prototype.change = function(index, number) {
if(this.global[index])
{
for(var key in this.obj)
{
let ind = this.obj[key].indexOf(index)
if(ind != -1)
... | Design a Number Container System |
Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.
Example 1:
Input: s = "owoztneoer"
Output: "012"
Example 2:
Input: s = "fviefuro"
Output: "45"
Constraints:
1 <= s.length <= 105
s[i] is one of the characters ["e","g","f","i... | class Solution:
def originalDigits(self, s: str) -> str:
c = dict()
c[0] = s.count("z")
c[2] = s.count("w")
c[4] = s.count("u")
c[6] = s.count("x")
c[8] = s.count("g")
c[3] = s.count("h") - c[8]
c[5] = s.count("f") - c[4]
c[7]... | class Solution {
// First letter is unique after previous entries have been handled:
static final String[] UNIQUES = new String[] {
"zero", "wto", "geiht", "xsi", "htree",
"seven", "rfou", "one", "vfie", "inne"
};
// Values corresponding to order of uniqueness checks:
static final ... | class Solution {
public:
vector<string> digits{"zero","one","two","three","four","five","six","seven","eight","nine"};
void fun(int x,string &ans,vector<int> &m){
for(int i = x;i<=9;i+=2){
string t = digits[i];
if(t.length() == 3){
if(m[t[0]-'a'] > 0 && m[t[1... | /**
* @param {string} s
* @return {string}
*/
var originalDigits = function(s) {
const numberToWord = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine'
}
con... | Reconstruct Original Digits from English |
A binary tree is named Even-Odd if it meets the following conditions:
The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to ... | from collections import deque
# O(n) || O(h); where h is the height of the tree
class Solution:
def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:
if not root:
return False
level = 0
evenOddLevel = {0:1, 1:0}
queue = deque([root])
while queue:
... | class Solution {
public boolean isEvenOddTree(TreeNode root) {
Queue<TreeNode> qu = new LinkedList<>();
qu.add(root);
boolean even = true; // maintain check for levels
while(qu.size()>0){
int size = qu.size();
int prev = (even)?0:Integer.MAX_VALUE; // start pr... | class Solution {
public:
bool isEvenOddTree(TreeNode* root) {
queue<TreeNode*>q;
vector<vector<int>>ans;
if(root==NULL) return true;
q.push(root);
int j=0;
while(q.empty()!=true)
{ vector<int>v;
int n=q.size();
for(int i=0;i<n;i++)
... | /**
* 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 {boolean}
*/
var isEvenOddTree = ... | Even Odd Tree |
A super ugly number is a positive integer whose prime factors are in the array primes.
Given an integer n and an array of integers primes, return the nth super ugly number.
The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
Example 1:
Input: n = 12, primes = [2,7,13,19]
Output: 32
Exp... | class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
prime_nums = len(primes)
index = [1]*prime_nums
ret = [1]*(n+1)
for i in range(2,n+1):
ret[i] = min(primes[j]*ret[index[j]] for j in range(prime_nums))
for k in range(prime_nums):
if ret[i] == pri... | //---------------------O(nlogk)-------------------------
class Solution {
public int nthSuperUglyNumber(int n, int[] primes) {
int []dp=new int[n+1];
dp[1]=1;
PriorityQueue<Pair> pq=new PriorityQueue<>();
for(int i=0;i<primes.length;i++){
pq.add(new Pai... | Time: O(n*n1) Space: O(n)
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
if(n==1)
return 1;
vector<long long int> dp(n);
dp[0]=1;
int n1=size(primes);
vector<int> p(n1);
for(int i=1;i<n;i++){
long long int x=IN... | var nthSuperUglyNumber = function(n, primes) {
const table = Array(primes.length).fill(0);
const res = Array(n);
res[0] = 1;
for(let j=1;j<n;j++){
let curr = Infinity;
for (let i=0;i< table.length; i++) {
curr = Math.min(curr, res[table[i]]*primes[i]);
}
for (... | Super Ugly Number |
Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.
Example 1:
Input: nums = ["777","7","77","77"], target = "7777"
Output: 4
Explanation: Valid pairs are:
- (0, 1): "777" + "... | class Solution:
def numOfPairs(self, nums, target):
return sum(i + j == target for i, j in permutations(nums, 2)) | class Solution {
public int numOfPairs(String[] nums, String target) {
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i<nums.length; i++){
map.put(nums[i], map.getOrDefault(nums[i],0)+1);
}
int ans = 0, n = target.length();
Strin... | class Solution {
public:
int numOfPairs(vector<string>& nums, string target) {
unordered_map<string, int> freq;
for (auto num : nums) if (num.size() < target.size()) freq[num]++;
int res = 0;
for (auto [s, frq] : freq) {
if (target.find(s) == 0) {
... | /**
* @param {string[]} nums
* @param {string} target
* @return {number}
*/
var numOfPairs = function(nums, target) {
var count = 0;
var x = 0;
while (x < nums.length) {
for (let y = 0; y<nums.length; y++) {
if (nums[x] + nums[y] == target) {
count += 1;
... | Number of Pairs of Strings With Concatenation Equal to Target |
Given an array of integers arr, sort the array by performing a series of pancake flips.
In one pancake flip we do the following steps:
Choose an integer k where 1 <= k <= arr.length.
Reverse the sub-array arr[0...k-1] (0-indexed).
For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k =... | class Solution:
def pancakeSort(self, arr: List[int]) -> List[int]:
#helper function to flip the numbers in the array
def flip(i, j):
while i < j:
arr[i], arr[j] = arr[j], arr[i]
j -= 1
i += 1
#sort from 0 to i
def sort(i... | // BruteForce Approach!
// Author - Nikhil Sharma
// LinkedIn - https://www.linkedin.com/in/nikhil-sharma-41a287226/
// Twitter - https://twitter.com/Sharma_Nikh12
class Solution {
public List<Integer> pancakeSort(int[] arr) {
List<Integer> list = new ArrayList<>();
int n = arr.length;
whil... | class Solution {
private:
void reverse(vector<int>&arr,int start,int end){
while(start<end){
swap(arr[start++],arr[end--]);
}
}
public:
vector<int> pancakeSort(vector<int>& arr) {
vector<int>copy=arr;
sort(copy.begin(),copy.end());
int end=copy.size()-1;
... | var pancakeSort = function(arr) {
let res = [];
for(let i=arr.length; i>0; i--){//search the array for all values from 1 to n
let idx = arr.indexOf(i);
if(idx!=i-1){// if value is not present at its desired index
let pancake = arr.slice(0,idx+1).reverse();//flip the array with k=index of value i to put... | Pancake Sorting |
Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.
Example 1:
Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".
Ex... | class Solution:
def maxProduct(self, words: List[str]) -> int:
def check(w1, w2):
for i in w1:
if i in w2:
return False
return True
n = len(words)
Max = 0
for i in range(n):
for j in range(i+1, n):
... | class Solution {
public int maxProduct(String[] words) {
int n = words.length;
int[] masks = new int[n];
for (int i=0; i<n; i++)
for (char c: words[i].toCharArray())
masks[i] |= (1 << (c - 'a'));
int largest = 0;
for (int i=0; i<n-1; i++)
... | class Solution {
public:
int maxProduct(vector<string>& words) {
vector<unordered_set<char>> st;
int res =0;
for(string s : words){
unordered_set<char> temp;
for(char c : s){
temp.insert(c);
}
st.push_back(temp);
}
... | /**
* @param {string[]} words
* @return {number}
*/
var maxProduct = function(words) {
words.sort((a, b) => b.length - a.length);
const m = new Map();
for(let word of words) {
if(m.has(word)) continue;
const alpha = new Array(26).fill(0);
for(let w of word) {
let ... | Maximum Product of Word Lengths |
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.ri... | # class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:
temp1=temp2=float(inf)
from collections import deque
a... | class Solution {
int ans = Integer.MAX_VALUE;
boolean x = true;
public int findSecondMinimumValue(TreeNode root) {
go(root);
return x ? -1 : ans;
}
private void go(TreeNode root) {
if (root == null) return;
if (root.left != null) {
if (root.left.val == r... | class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
queue<TreeNode*>q;
q.push(root);
vector<int>v;
while(!q.empty()){
v.push_back(q.front()->val);
if(q.front()->left){
q.push(q.front()->left);
}
if(q.fr... | var findSecondMinimumValue = function(root) {
let firstMin=Math.min()
let secondMin=Math.min()
const que=[root]
while(que.length){
const node=que.shift()
if(node.val<=firstMin){
if(node.val<firstMin)secondMin=firstMin
firstMin=node.val
}else i... | Second Minimum Node In a Binary Tree |
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:
Input: p = [1,2], q = [1,nul... | class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
elif not p or not q:
return False
else:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) | class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
// Base case: if both trees are null, they are identical
if (p == null && q == null) {
return true;
}
// If only one tree is null or the values are different, they are not identical
if (p == null... | class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == NULL || q == NULL) return q == p;
if(p->val != q->val) return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
}; | var isSameTree = function(p, q) {
const stack = [p, q];
while (stack.length) {
const node2 = stack.pop();
const node1 = stack.pop();
if (!node1 && !node2) continue;
if (!node1 && node2 || node1 && !node2 || node1.val !== node2.val) {
return false;
... | Same Tree |
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any tw... | class Solution:
def possible (self,distance,positions,M):
ball = 1
lastPos = positions[0]
for pos in positions:
if pos-lastPos >= distance:
ball+=1
if ball == M: return True
lastPos=pos
return False
def maxDistance(self, positions,M):
... | class Solution {
public int maxDistance(int[] position, int m) {
Arrays.sort(position);
int low=Integer.MAX_VALUE;
int high=0;
for(int i=1;i<position.length;i++){
low=Math.min(low,position[i]-position[i-1]);
}
high=position[position.length-1]-position[0];
... | class Solution {
public:
bool isPossible(vector<int>& position, int m,int mid){
long long int basketCount=1;
int lastPos=position[0];
for(int i=0;i<position.size();i++){
if((position[i]-lastPos)>=mid){
basketCount++;
lastPos=position[i];
... | var maxDistance = function(position, m) {
position = position.sort((a, b) => a - b);
function canDistribute(n) {
let count = 1;
let dist = 0;
for(let i = 1; i < position.length; i++) {
dist += position[i] - position[i - 1];
if (dist >= n) {
... | Magnetic Force Between Two Balls |
You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the NestedIterator class:
NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested l... | class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.flattened_lst = self.flattenList(nestedList)
self.idx = 0
def next(self) -> int:
if self.idx >= len(self.flattened_lst):
raise Exception("Index out of bound")
self.idx += 1
return... | public class NestedIterator implements Iterator<Integer> {
List<Integer> list=new ArrayList();
void flatten(List<NestedInteger> nestedList){
for(NestedInteger nested:nestedList){
if(nested.isInteger())
list.add(nested.getInteger());
else
flatten(ne... | class NestedIterator {
vector<int> v;
int index;
void helper(vector<NestedInteger> &nestedList, vector<int>& v)
{
for (int i = 0; i < nestedList.size(); i++)
{
if (nestedList[i].isInteger())
{
v.push_back(nestedList[i].getInteger());
}
... | /**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* function NestedInteger() {
*
* Return true if this NestedInteger holds a single integer, rather than a nested list.
* @return {boolean}
* this.isInteger = fu... | Flatten Nested List Iterator |
Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]
Constraints:
n == nums.length
1 <= n <... | class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
return set(nums) ^ set(range(1,len(nums)+1)) | class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<>();
// 0 1 2 3 4 5 6 7 <- indx
// 4 3 2 7 8 2 3 1 <- nums[i]
for(int i=0;i<nums.length;i++) {
int indx = Math.abs(nums[i])-1;
if(nums[indx]>0) {
... | class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
int n = nums.size();
for (int i = 0; i < n; i++) {
if (nums[abs(nums[i]) - 1] > 0) {
nums[abs(nums[i]) - 1] *= -1;
}
}
for (int i = 0; i <... | var findDisappearedNumbers = function(nums) {
let result = [];
for(let i = 0; i < nums.length; i++) {
let id = Math.abs(nums[i]) - 1;
nums[id] = - Math.abs(nums[id]);
}
for(let i = 0; i < nums.length; i++) {
if(nums[i] > 0) result.push(i + 1);
}
return result;
}; | Find All Numbers Disappeared in an Array |
The appeal of a string is the number of distinct characters found in the string.
For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'.
Given a string s, return the total appeal of all of its substrings.
A substring is a contiguous sequence of characters within a string.
... | class Solution:
def appealSum(self, s: str) -> int:
res, cur, prev = 0, 0, defaultdict(lambda: -1)
for i, ch in enumerate(s):
cur += i - prev[ch]
prev[ch] = i
res += cur
return res | class Solution {
public long appealSum(String s) {
long res = 0;
char[] cs = s.toCharArray();
int n = cs.length;
int[] pos = new int[26];
Arrays.fill(pos, -1);
for (int i = 0; i < n; ++i) {
int j = cs[i] - 'a', prev = pos[j];
res += (i - prev)... | class Solution {
public:
long long appealSum(string s) {
int n = s.size();
long long ans = 0;
for(char ch='a';ch<='z';ch++) // we are finding the number of substrings containing at least 1 occurence of ch
{
int prev = 0; // prev will store the previous index of the charcter ch
for... | var appealSum = function(s) {
let ans = 0, n = s.length;
let lastIndex = Array(26).fill(-1);
for (let i = 0; i < n; i++) {
let charcode = s.charCodeAt(i) - 97;
let lastIdx = lastIndex[charcode];
ans += (n - i) * (i - lastIdx);
lastIndex[charcode] = i;
}
return ans;
}; | Total Appeal of A String |
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,1... | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
for i in range(n - 1):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
return [] # No solution found | class Solution {
public int[] twoSum(int[] nums, int target) {
int[] answer = new int[2];
// Two for loops for selecting two numbers and check sum equal to target or not
for(int i = 0; i < nums.length; i++){
for(int j = i+1; j < nums.length; j++) {
// j = i + 1; no need to check... | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
... | /**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var sol = [];
var found = 0;
for(let i = 0; i < nums.length; i ++) {
for(let j = i + 1; j < nums.length; j ++) {
if(nums[i] + nums[j] === target) {
sol.... | Two Sum |
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.
Example 1:
Input: nums = [4,14,2]
Output: 6
Explanation: In binary representation,... | class Solution:
def totalHammingDistance(self, arr: List[int]) -> int:
total = 0
for i in range(0,31):
count = 0
for j in arr :
count+= (j >> i) & 1
total += count*(len(arr)-count)
return total | class Solution {
public int totalHammingDistance(int[] nums) {
int total = 0;
int[][] cnt = new int[2][32];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < 32; j++) {
int idx = (nums[i] >> j) & 1;
total += cnt[idx ^ 1][j];
... | /*
So in the question we want to find out the
number of difference of bits between each pair
so in the brute force we will iterate over the vector
and for every pair we will calculate the Hamming distance
the Hamming distance will be calculated by taking XOR between the two elements
and then finding out the numbe... | var totalHammingDistance = function(nums) {
let n = nums.length, ans = 0;
for(let bit = 0; bit < 32; bit++) {
let zeros = 0, ones = 0;
for(let i = 0; i < n; i++) {
((nums[i] >> bit) & 1) ? ones++ : zeros++;
}
ans += zeros * ones;
}
return ans;
}; | Total Hamming Distance |
You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
The blue edges and nodes in the following figure indicate the result:
Build the result list and return its head.
Example 1:
Input: list1 = [0,1... | class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
head = list1
for _ in range(a-1):
head = head.next
cur = head.next
for _ in range(b-a):
cur = cur.next
head.next = list2
while head.next:
... | class Solution {
public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
ListNode left = list1;
for (int i = 1; i < a; i++)
left = left.next;
ListNode middle = left;
for (int i = a; i <= b; i++)
middle = middle.next;
... | class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
int jump1 = 1;
ListNode *temp1 = list1;
while (jump1 < a){
temp1 = temp1->next;
jump1++;
} //Gets the pointer to a
... | var mergeInBetween = function(list1, a, b, list2) {
let start = list1;
let end = list1;
for (let i = 0; i <= b && start != null && end != null; i++) {
if (i < a - 1) start = start.next;
if (i <= b) end = end.next;
}
let tail = list2;
while (tail.next != null) {
tail = ... | Merge In Between Linked Lists |
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way ... | from heapq import heappush, heappop, nlargest
class Solution:
def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
if w >= max(capital):
return w + sum(nlargest(k, profits))
projects = [[capital[i],profits[i]] for i in range(len(profits)... | class Solution {
static int[][] dp;
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
dp = new int[k + 1][profits.length + 1];
for (int[] row : dp) {
Arrays.fill(row, -1);
}
return w + help(k, w, 0, profits, capital);
}
public int help(int k, int w, int i, int[] profits, int... | class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pqsg;
priority_queue<pair<int, int>> pqgs;
int n = capital.size();
for(int i = 0; i < n; i++)
... | var findMaximizedCapital = function(k, w, profits, capital) {
let capitals_asc_queue = new MinPriorityQueue();
let profits_desc_queue = new MaxPriorityQueue();
for (let i = 0; i < capital.length; i++)
capitals_asc_queue.enqueue([capital[i], profits[i]], capital[i]);
for (let i = 0; i < k; i++) ... | IPO |
There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.
When withdrawing, the machine prioritizes using banknotes of larger values.
For example, if you want to withdraw $... | class ATM:
def __init__(self):
self.cash = [0] * 5
self.values = [20, 50, 100, 200, 500]
def deposit(self, banknotes_count: List[int]) -> None:
for i, n in enumerate(banknotes_count):
self.cash[i] += n
def withdraw(self, amount: int) -> List[int]:
res = []
... | class ATM {
long[] notes = new long[5]; // Note: use long[] instead of int[] to avoid getting error in large testcases
int[] denoms;
public ATM() {
denoms = new int[]{ 20,50,100,200,500 }; // create an array to represent money value.
}
... | class ATM {
public:
long long bank[5] = {}, val[5] = {20, 50, 100, 200, 500};
void deposit(vector<int> banknotesCount) {
for (int i = 0; i < 5; ++i)
bank[i] += banknotesCount[i];
}
vector<int> withdraw(int amount) {
vector<int> take(5);
for (int i = 4; i >= 0; --i) {
... | var ATM = function() {
this.bankNotes = new Array(5).fill(0)
this.banksNotesValue = [20, 50, 100, 200, 500]
};
/**
* @param {number[]} banknotesCount
* @return {void}
*/
ATM.prototype.deposit = function(banknotesCount) {
for (let i = 0; i < 5; i++) {
this.bankNotes[i] += banknotesCount[i]
}
... | Design an ATM Machine |
You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.
A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.
Return the number of land cells in grid for which we cannot walk off the boundar... | class Solution:
def recursion(self, grid, row, col, m, n):
if 0<=row<m and 0<=col<n and grid[row][col] == 1:
grid[row][col] = 't'
self.recursion(grid, row+1, col, m, n)
self.recursion(grid, row-1, col, m, n)
self.recursion(grid, row, col+1, m, n)
s... | class Solution {
public int numEnclaves(int[][] grid) {
int maxcount = 0;
// if(grid.length==10)
// {
// return 3;
// }
for(int i = 0;i<grid.length;i++)
{
for(int j = 0;j<grid[0].length;j++)
{
if(grid[i][j] =... | class Solution {
public:
int numEnclaves(vector<vector<int>>& grid) {
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[0].size();j++)
{
if(grid[i][j]==0)
continue;
int c=0;
if(grid[i][j]==1 && (i*j==0 || i... | /**
* @param {number[][]} grid
* @return {number}
*/
var numEnclaves = function(grid) {
let count = 0, rowLength = grid.length, colLength = grid[0].length
const updateBoundaryLand = (row,col) => {
if(grid?.[row]?.[col]){
grid[row][col] = 0
updateBoundaryLand(row + 1,col)
... | Number of Enclaves |
You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'.
Each move in this game consists of choosing a free cell and changing it to the color you... | class Solution:
def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:
directions = [False] * 8
moves = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0),
(-1, -1), (0, -1), (1, -1)]
opposite_color = "W" if color == "B" else "B"
for d in ra... | class Solution {
public boolean checkMove(char[][] board, int rMove, int cMove, char color) {
int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};
for(int[] d : direction)
{
if(dfs(board,rMove,cMove,color,d,1))
return true;... | class Solution {
public:
bool inBoard(vector<vector<char>>& board, int x, int y) {
return x >= 0 && x < board.size() && y >= 0 && y < board[0].size();
}
bool isLegal(vector<vector<char>>& board, int x, int y, char color) {
if (color == 'B') return board[x][y] == 'W';
if (color =... | var checkMove = function(board, rMove, cMove, color) {
const moves = [-1, 0, 1];
let count = 0;
for (let i = 0; i < 3; ++i) {
for (let j = 0; j < 3; ++j) {
if (i === 1 && j === 1) continue;
const rowDir = moves[i];
const colDir = moves[j];
... | Check if Move is Legal |
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return the maximum number of envelopes you... | from bisect import bisect_left
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes = sorted(envelopes, key= lambda x:(x[0],-x[1]))
rst = []
for _,h in envelopes:
i = bisect_left(rst,h)
if i == len(rst):
rst.append(h)
... | class Solution {
public int maxEnvelopes(int[][] envelopes) {
//sort the envelopes considering only width
Arrays.sort(envelopes, new sortEnvelopes());
//Now this is a Longest Increasing Subsequence problem on heights
//tempList to store the temporary elements, size of this list will be the length o... | class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
int n = envelopes.size();
sort(envelopes.begin(), envelopes.end(), [](auto &l, auto &r)
{
return l[0] == r[0] ? l[1] > r[1] : l[0] < r[0];
});
int len = 0;
for(auto& ... | const binarySearch = (arr, target) => {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else ... | Russian Doll Envelopes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.