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
Output: []
Constraints:
The number of nodes in the list is in the range [0, 104].
1 <= Node.val <= 50
0 <= val <= 50
| # 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.val==val:
if cur==head:
head=head.next
prev=head
else:
prev.next=cur.next
else:
prev=cur
cur=cur.next
return head | 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 {
head = head.next;
}
}
if (result.val == val) {
result = result.next;
}
return result;
}
} | 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;
while(cur){
if(cur->val==val){
temp=cur;
prv->next=cur->next;
cur=cur->next;
delete(temp);
}
else{
prv=cur;
cur=cur->next;
}
}
return head;
}
}; | /**
* 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(!head)return null
//if the val is on the beginning delete it
while( head && head.val===val)head=head.next
let current=head;
let next=head.next;
//travers the liste and delete any node has this val
while(next){
if(next.val===val){
current.next=next.next
}
else current=next
next=next.next
}
return head
}; | 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 that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n.
Return the state of the prison after n days (i.e., n such changes described above).
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], n = 7
Output: [0,0,1,1,0,0,0,0]
Explanation: The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], n = 1000000000
Output: [0,0,1,1,1,1,1,0]
Constraints:
cells.length == 8
cells[i] is either 0 or 1.
1 <= n <= 109
| 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('0') # left corner case
for c in range(1,totalPrisons-1):
if (cells[c-1]=='1' and cells[c+1]=='1') or (cells[c-1]=='0' and cells[c+1]=='0'):
tempCell.append('1') # insert 1 if first condition met
else:
tempCell.append('0') # otherwise 0
tempCell.append('0') # right corner case
cells=tempCell # update cells
pattern= ''.join(tempCell) # insert pattern in hashtable
if pattern in patternMatch: # if there is a match
day=patternMatch[pattern]
remainder= (n%(d-1))-1 # take modulo
match= list(patternMatch.keys())[remainder] # find key
return [ int(m) for m in match] # return
patternMatch[pattern]=d # assign day
return [ int(c) for c in (cells)] # return | 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 is bigger than 14
// # - You do a first round of 14 iteration
// # - Than you do a second round of n%14 iteration
// # ===> O(27)
n = n % 14 == 0 ? 14 : n%14;
int temp[] = new int[cells.length];
while(n-- > 0)
{
for(int i=1; i <cells.length- 1; i++)
{
temp[i] = cells[i-1] == cells[i+1]? 1: 0;
}
cells = temp.clone();
}
return cells;
}
} | 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<cells.size();i++){
if(cells[i]){
state^=(1<<(7-i));
}
}
//this array stores the various states encountered
vector<int>seen;
while(n--){
int next=0;
//transitioning to the next state
for(int pos=6;pos>0;pos--){
int right=pos+1,left=pos-1;
if(((state>>right)&1)==((state>>left)&1)){
next|=(1<<pos);
}
}
//if the next state is equal to the initial state, this means that we have
//found the cycle. Let the length of the cycle be l=seen.size(). Therefore
//in the remaining n days, n/l of those will have no effect on the
//prison configuration. This means we can return the configuration of the
//n%l day.
if(seen.size() and seen[0]==next){
int cnt=seen.size();
state=seen[n%cnt];
break;
} else {
seen.push_back(next);
state=next;
}
}
//translating the prison state from the bitmask to an array.
vector<int>ans(cells.size(),0);
for(int i=0;i<8;i++){
if((state>>i)&1){
ans[7-i]=1;
}
}
return ans;
}
}; | /**
* @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))){
set.add(String(nextCells))
cycleDuration++
cells = nextCells
} else {
// 2. Use cycle length to iterate once more to get to correct order
let remainderToMove = n%cycleDuration
while(remainderToMove >= 0) {
remainderToMove--
cells = getNextCells(cells)
}
break
}
}
return cells
};
function getNextCells(cells) {
let temp = [...cells]
for(let i = 0; i < 8; i++) {
if(i>0 && i < 7 && cells[i-1] === cells[i+1]) {
temp[i] = 1
} else {
temp[i] = 0
}
}
return temp
}
// 0
// 1
// 2
// n
// 1 000 000 % n | 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.
Repeat until there are no more slices of pizzas.
Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.
Example 1:
Input: slices = [1,2,3,4,5,6]
Output: 10
Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.
Example 2:
Input: slices = [8,9,8,6,1,1]
Output: 16
Explanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.
Constraints:
3 * n == slices.length
1 <= slices.length <= 500
1 <= slices[i] <= 1000
| 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==0:
return 0
if dp[start][n] !=-1:
return dp[start][n]
include = slices[start] + solve(slices,start+2,end,n-1,dp)
exclude = 0 + solve(slices,start+1,end,n,dp)
dp[start][n]= max(include,exclude)
return dp[start][n]
dp1=[[-1 for i in range(k+1)]for _ in range(k+1)]
dp2=[[-1 for i in range(k+1)]for _ in range(k+1)]
option1=solve(slices,0,k-2,k//3,dp1)#Taking the the first slice , now we cant take the last slice and next slice
option2=solve(slices,1,k-1,k//3,dp2)#Taking the the second slice , now we cant take the second last slice and next slice
return max(option1,option2) | 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[][][] dp = new int[n][rounds+1][2];
dp[0][1][1] = slices[start];
for (int i = start + 1; i <= end; i++) {
int x = i - start;
for (int j = 1; j <= rounds; j++) {
dp[x][j][0] = Math.max(dp[x-1][j][0], dp[x-1][j][1]);
dp[x][j][1] = dp[x-1][j-1][0] + slices[i];
if (j == rounds) {
max = Math.max(max, Math.max(dp[x][j][0], dp[x][j][1]));
}
}
}
return max;
}
} | 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 = solve(v,i+1,count) ;
return dp[i][count] = max(pick,notPick) ;
}
int maxSizeSlices(vector<int>& slices) {
vector<int>v1 ;
vector<int>v2 ;
for(int i = 0 ; i < slices.size() ;i++){
if( i != slices.size()-1 ) v1.push_back(slices[i]) ;
if( i != 0 ) v2.push_back(slices[i]);
}
memset(dp,-1,sizeof(dp)) ;
int ans1 = solve(v1,0,0);
memset(dp,-1,sizeof(dp)) ;
int ans2 = solve(v2,0,0);
return max(ans1,ans2) ;
}
}; | 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
dp[0][1] = pieces[0];
// the max for 1 piece using the first 2 slices is the max of the first and second slice
dp[1][1] = Math.max(pieces[0], pieces[1]);
// start the max as the max of taking 1 slice from the first 2 slices
let max = dp[1][1];
// calculate the max value for taking x number of pieces using up to that piece
for (let i = 2; i < pieces.length; i++) {
for (let numPieces = 1; numPieces <= numSlices; numPieces++) {
dp[i][numPieces] = Math.max(dp[i - 1][numPieces], // the max for not taking this piece
dp[i - 2][numPieces - 1] + pieces[i]); // the max for taking this piece
if (max < dp[i][numPieces]) max = dp[i][numPieces]; // update the max if it is greater
}
}
return max;
}
return Math.max(getMaxTotalSlices(slices.slice(0, slices.length - 1)), // get max without the last slice
getMaxTotalSlices(slices.slice(1))); // get max without the first slice
}; | 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 island in grid. If there is no island, return 0.
Example 1:
Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j] is either 0 or 1.
| 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]] = [[False for _ in range(cols)] for _ in range(rows)]
for i in range(rows):
for j in range(cols):
if not visited[i][j] and grid[i][j]:
res = self.dfs(grid, visited, i, j)
ans = res if res > ans else ans
return ans
def dfs(self, grid: List[List[int]], visited: List[List[bool]], startRow: int, startCol: int) -> int:
[rows, cols] = [len(grid), len(grid[0])]
fields = 1
q = Queue()
q.put([startRow, startCol])
visited[startRow][startCol] = True
while not q.empty():
[row, col] = q.get()
for d in self.directions:
newRow = row + d[0]
newCol = col + d[1]
if newRow >= 0 and newRow < rows and newCol >= 0 and newCol < cols and not visited[newRow][newCol] and grid[newRow][newCol]:
visited[newRow][newCol] = True
fields += 1
q.put([newRow, newCol])
return fields | 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];
Queue<String> queue=new LinkedList<>();
int res=0;
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[i].length;j++)
{
List<int[]> list=new ArrayList<>();
for(int[] dirrection:dirrections)
{
int newRow=dirrection[0]+i;
int newCol=dirrection[1]+j;
boolean isInBoard=newRow>=rows||newRow<0||newCol>=cols||newCol<0;
if(!isInBoard)
{
list.add(new int[]{newRow,newCol,grid[newRow][newCol]});
}
}
adj.put(getNodeStringFormat(i,j,grid[i][j]),list);
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
int count=0;
if(visited[i][j])
continue;
queue.add(getNodeStringFormat(i,j,grid[i][j]));
while(!queue.isEmpty())
{
String currentStr=queue.poll();
String[] current=currentStr.split(",");
int row=Integer.valueOf(current[0]);
int col=Integer.valueOf(current[1]);
int isLand=Integer.valueOf(current[2]);
if(!adj.containsKey(currentStr))
continue;
if(visited[row][col])
continue;
if(isLand==1)
count++;
visited[row][col]=true;
for(int[] item:adj.get(currentStr))
{
int newRow=item[0];
int newCol=item[1];
int newIsLand=item[2];
if(!visited[newRow][newCol] && newIsLand==1 && isLand==1)
queue.add(getNodeStringFormat(newRow,newCol,newIsLand));
}
}
res=Math.max(res,count);
}
}
return res;
}
private String getNodeStringFormat(int row,int col,int isLand)
{
StringBuilder sb=new StringBuilder();
sb.append(row);
sb.append(",");
sb.append(col);
sb.append(",");
sb.append(isLand);
return sb.toString();
}
} | 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(vector<vector<int>>& grid) {
int m=grid.size(),n=grid[0].size(),maxArea=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==1){
int area=0;
area=cal(grid,i,j,m,n);
maxArea=max(maxArea,area);
}
}
}
return maxArea;
}
}; | 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;
grid[m][n] = 'X';
const top = dfs(m - 1, n);
const bottom = dfs(m + 1, n);
const left = dfs(m, n - 1);
const right = dfs(m, n + 1);
return 1 + top + bottom + left + right;
};
for (let m = 0; m < M; m++) {
for (let n = 0; n < N; n++) {
if (!island(m, n)) continue;
const area = dfs(m, n);
result = Math.max(area, result);
}
}
return result;
}; | 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 string that is palindromic is "ada".
Note that "racecar" is also palindromic, but it is not the first.
Example 2:
Input: words = ["notapalindrome","racecar"]
Output: "racecar"
Explanation: The first and only string that is palindromic is "racecar".
Example 3:
Input: words = ["def","ghi"]
Output: ""
Explanation: There are no palindromic strings, so the empty string is returned.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] consists only of lowercase English letters.
| 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) {
for(int i=0 ; i<words.size() ; i++){
if(isPalindrome(words[i]))
return words[i];
}
return "";
}
}; | 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 = k.
The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.
We stop adding right before a duplicate element occurs in s[k].
Return the longest length of a set s[k].
Example 1:
Input: nums = [5,4,0,3,1,6,2]
Output: 4
Explanation:
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
Example 2:
Input: nums = [0,1,2]
Output: 1
Constraints:
1 <= nums.length <= 105
0 <= nums[i] < nums.length
All the values of nums are unique.
| 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.add(index)
dfs_visited.add(index)
return dfs(nums, nums[index], dfs_visited)
for i in range(len(nums)):
if i not in visited:
max_len = max(max_len, dfs(nums, i, set()))
return max_len | 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);
}
}
return res;
}
public int dfs(int[] nums,int i,boolean[] visited){
if(visited[i]) return 0;
visited[i] = true;
return 1+dfs(nums,nums[i],visited);
}
} | 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(int i=0;i<nums.size();i++)
arr[i]=0;
for(int i=0;i<nums.size();i++)
{
int res=dfs(nums,i,arr,0);
ans=max(res,ans);
}
return ans;
}
}; | 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 = 1 + 2 + 3 + 4 + 5
Constraints:
1 <= n <= 109
| # 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 + 3 + 4 + 5 = 4 * 3.5
#
# So n can be written as
#
# n = (even length) * (half-integer average)
# = (2 * c) * (d / 2)
# = c * d
#
# for some arbitrary integer c and odd integer d. So again, any odd d divisor of
# n produces an even length sum, and every even length sum is of this form.
#
# However, we need to ensure that the sum only contains positive integers.
#
# For the first case, the smallest number is n/d - (d-1)/2. For the second case,
# it's (d+1)/2 - n/d.
#
# For all d, exactly one of these is positive, and so every odd divisor
# corresponds to exactly one sum, and all sums are of this form.
#
# Therefore, we need to count the odd divisors.
#
# There's no way I know of doing this without essentially factoring the number.
# So say
#
# n = 2**n0 * p1**n1 * p2**n2 * ... * pk**nk
#
# is the prime decomposition (all p are odd). Then n has
#
# (n1+1) * (n2+1) * ... * (nk+1)
#
# odd divisors.
#
# For the implementation, we search the smallest divisor, which is neccessarily
# prime and divide by it as often as possible (and count the divisions). If
# after that p**2 > n, we know that n itself is prime.
#
# Complexity is O(sqrt(n)) in bad cases (if n is prime), but can be much better
# if n only has small prime factors, e.g. for n = 3**k it's O(k) = O(log(n)).
class Solution:
def consecutiveNumbersSum(self, n: int) -> int:
while n % 2 == 0:
# Kill even factors
n //= 2
result = 1
p = 3
while n != 1:
count = 1
while n % p == 0:
n //= p
count += 1
result *= count
if p**2 >= n:
# Rest of n is prime, stop here
if n > p:
# We have not counted n yet
result *= 2
break
p += 2
return result | 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 m = 2; m <= maxTriangular; ++m) {
triangular += m;
final int difference = n - triangular;
if ((difference % m) == 0) {
ways++;
}
}
return ways;
}
} | 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++;
}
}
return 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 contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).
Example 1:
Input: nums = [4,2,4,5,6]
Output: 17
Explanation: The optimal subarray here is [2,4,5,6].
Example 2:
Input: nums = [5,2,1,2,5,2,1,2,5]
Output: 8
Explanation: The optimal subarray here is [5,2,1] or [1,2,5].
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 104
| 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
curr_sum += nums[r]
seen.add(nums[r])
r += 1
max_sum = max(max_sum, curr_sum)
return max_sum | 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) {
nmap[nums[left]]--;
total -= nums[left++];
}
best = Math.max(best, total);
}
return best;
}
} | 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 we reach the repeating element
st.erase(nums[i]);
curr_sum-=nums[i];
i++;
}
//Add the current element to set and curr_sum value
curr_sum+=nums[j];
st.insert(nums[j++]);
//res variable to keep track of largest curr_sum encountered till now...
res = max(res, curr_sum);
}
return res;
}
}; | 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++]
best = Math.max(best, total)
}
return best
}; | 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 symbol character is '.
Ampersand: the entity is &amp; and symbol character is &.
Greater Than Sign: the entity is &gt; and symbol character is >.
Less Than Sign: the entity is &lt; and symbol character is <.
Slash: the entity is &frasl; and symbol character is /.
Given the input text string to the HTML parser, you have to implement the entity parser.
Return the text after replacing the entities by the special characters.
Example 1:
Input: text = "&amp; is an HTML entity but &ambassador; is not."
Output: "& is an HTML entity but &ambassador; is not."
Explanation: The parser will replace the &amp; entity by &
Example 2:
Input: text = "and I quote: &quot;...&quot;"
Output: "and I quote: \"...\""
Constraints:
1 <= text.length <= 105
The string may contain any possible characters out of all the 256 ASCII characters.
| class Solution:
def entityParser(self, text: str) -> str:
d = {""" : '"' , "'":"'" , "&" : "&" , ">" : ">" , "<":"<" , "⁄" : "/"}
ans = ""
i = 0
while i < len(text):
bag = ""
#condition if find & and next char is not & also and handdling index out of range for i + 1
if i+1 < len(text) and text[i] == "&" and text[i+1] != "&":
#create subtring for speacial char till ";"
for j in range(i , len(text)):
if text[j] == ";":
bag += text[j]
break
else:
bag += text[j]
#if that not present in dict we added same as it is
if bag not in d:
ans += bag
else:
ans += d[bag]
#increment by length of bag
i += len(bag)
#otherwise increment by 1
else:
ans += text[i]
i += 1
return ans
| 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]=='&'){
int j = i;
string com ="";
while(text[j]!=';' && j<text.size()){
com+=text[j];
j++;
}
com+=text[j];
if(mp.find(com)!=mp.end()){
text.erase(i,j-i);
text[i] = mp[com];
}
}
}
return text;
}
}; | /**
* @param {string} text
* @return {string}
*/
var entityParser = function(text) {
const entityMap = {
'"': `"`,
''': `'`,
'&': `&`,
'>': `>`,
'<': `<`,
'⁄': `/`
}
stack = [], entity = "";
for(const char of text) {
stack.push(char);
if(char == '&') {
if(entity.length > 0) entity = "";
entity += char;
}
else if(char == ';' && entity.length > 0) {
entity += char;
if(entity in entityMap) {
while(stack.length && stack[stack.length - 1] !== '&') {
stack.pop();
}
stack.pop();
stack.push(entityMap[entity]);
}
entity = "";
}
else if(entity.length > 0) {
entity += char;
}
}
return stack.join('');
}; | 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 first word (minimum index). If there is no such word return -1.
A prefix of a string s is any leading contiguous substring of s.
Example 1:
Input: sentence = "i love eating burger", searchWord = "burg"
Output: 4
Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.
Example 2:
Input: sentence = "this problem is an easy problem", searchWord = "pro"
Output: 2
Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
Example 3:
Input: sentence = "i am tired", searchWord = "you"
Output: -1
Explanation: "you" is not a prefix of any word in the sentence.
Constraints:
1 <= sentence.length <= 100
1 <= searchWord.length <= 10
sentence consists of lowercase English letters and spaces.
searchWord consists of lowercase English letters.
| 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 searchWord == word[0:len(searchWord)]:
return counter
return -1 | 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)){
for(int j=0;j<searchWord.length();j++){
if(str[i].charAt(j)!=searchWord.charAt(j)){
y=true;
break;
}
}
if(!y){
return i+1;
}
}
y=false;
}
return -1;
}
} | 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 stones are currently at positions x, y, and z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y.
The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).
Return an integer array answer of length 2 where:
answer[0] is the minimum number of moves you can play, and
answer[1] is the maximum number of moves you can play.
Example 1:
Input: a = 1, b = 2, c = 5
Output: [1,2]
Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.
Example 2:
Input: a = 4, b = 3, c = 2
Output: [0,0]
Explanation: We cannot make any moves.
Example 3:
Input: a = 3, b = 5, c = 1
Output: [1,2]
Explanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.
Constraints:
1 <= a, b, c <= 100
a, b, and c have different values.
| 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){
Arrays.sort(arr);
int count = 0;
if(arr[0] == (arr[1]-1) && arr[1] == (arr[2] -1) ) return count;
if(arr[0] == arr[1]-1){
arr[2]--;
count++;
}
else{
arr[0]++;
count++;
}
return count + findMaximum(arr);
}
public int findMinimum(int max,int[] arr){
Arrays.sort(arr);
if(max == 0) return 0;
else if(Math.abs(arr[0]-arr[1]) >2 && Math.abs(arr[1]-arr[2]) >2 ) return 2;
else return 1;
}
} | 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;
}
else if(arr[1] - arr[0] <= 2 || arr[2] - arr[1] <= 2)
{
mini = 1;
}
else
{
mini = 2;
}
// find maximum moves
int maxi = (arr[1] - arr[0] - 1) + (arr[2] - arr[1] - 1);
return {mini, maxi};
}
}; | 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 > 1) return [2, maxMoves];
return [1, maxMoves];
}; | 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 to target(2).
Example 2:
Input: nums = [-1,3,5,1,4,2,-9], target = 6
Output: 2
Explanation: There are 3 subarrays with sum equal to 6.
([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
0 <= target <= 106
| '''
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 += num
if prefix_sum - target in prefix_sums:
res += 1
# greedily discard prefix sums before num
# thus not considering subarrays that start at before num
prefix_sums = {prefix_sum}
else:
prefix_sums.add(prefix_sum)
return res | 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];
int pos = valToPos.getOrDefault(sums - target, -1);
if (pos >= lastEndPos) {
count += 1;
lastEndPos = i + 1;
}
valToPos.put(sums, i + 1);
}
return count;
}
} | 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) and mpp[sum-target] >= prev ) ++ways , prev = i ;
mpp[sum] = i ;
}
return ways ;
}
}; | 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(total)
}
return result;
}; | 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 difference between any two adjacent buildings cannot exceed 1.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti.
It is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.
Return the maximum possible height of the tallest building.
Example 1:
Input: n = 5, restrictions = [[2,1],[4,1]]
Output: 2
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.
Example 2:
Input: n = 6, restrictions = []
Output: 5
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.
Example 3:
Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]
Output: 5
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.
Constraints:
2 <= n <= 109
0 <= restrictions.length <= min(n - 1, 105)
2 <= idi <= n
idi is unique.
0 <= maxHeighti <= 109
| 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-2,-1,-1):
arr[i][1] = min(arr[i][1], arr[i+1][1]+arr[i+1][0]-arr[i][0])
res = 0
for i in range(1,n):
#position where height can be the highest between arr[i-1][0] and arr[i][0]
k = (arr[i][1]-arr[i-1][1]+arr[i][0]+arr[i-1][0])//2
res = max(res, arr[i-1][1]+k-arr[i-1][0])
return res | 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()-1)[0]!=n){
list.add(new int[]{n,n-1});
}
for(int i=1;i<list.size();i++){
list.get(i)[1]=Math.min(list.get(i)[1],list.get(i-1)[1] + list.get(i)[0]-list.get(i-1)[0]);
}
for(int i=list.size()-2;i>=0;i--){
list.get(i)[1]=Math.min(list.get(i)[1],list.get(i+1)[1] + list.get(i+1)[0] - list.get(i)[0]);
}
int result=0;
for(int i=1;i<list.size();i++){
int h1=list.get(i-1)[1]; // heigth of previous restriction
int h2=list.get(i)[1]; // height of current restriction
int x=list.get(i-1)[0]; // id of previous restriction
int y=list.get(i)[0]; // id of current restriction
result=Math.max(result,Math.max(h1,h2) + (y-x-Math.abs(h1-h2))/2);
}
return result;
}
public class IDSorter implements Comparator<int[]>{
@Override
public int compare(int[] myself,int[] other){
return myself[0]-other[0];
}
}
} | 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] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0]);
}
int ans = 0;
for (int i = 1; i < restrictions.size(); ++i) {
restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0]);
ans = max(ans, (restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0] + restrictions[i][1])/2);
}
return ans;
}
}; | /**
* @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){return a[0]-b[0]});
//Propogate from left to right to tighten the restriction: Check building restriction can be furhter tightened due to the left side building restriction.
for(let i=1;i<restrictions.length;i++){
restrictions[i][1] = Math.min(restrictions[i][1], (restrictions[i][0]-restrictions[i-1][0])+restrictions[i-1][1]);
}
//Propogate from right to left to tighten the restriction: Check building restriction can be furhter tightened due to the right side building restriction.
for(let i=restrictions.length-2;i>=0;i--){
restrictions[i][1] = Math.min(restrictions[i][1], (restrictions[i+1][0]-restrictions[i][0])+restrictions[i+1][1]);
}
let max=0;
for(let i=0;i<restrictions.length-1;i++){
let leftHeight = restrictions[i][1];
let rightHeight = restrictions[i+1][1];
let distance = restrictions[i+1][0]-restrictions[i][0]-1;//Number of cities between ith and i+1th city, excluding these cities
let hightDiff = Math.abs(restrictions[i+1][1]-restrictions[i][1]);
let middleHeight = Math.max(leftHeight,rightHeight)+Math.ceil((distance-hightDiff)/2);
max = Math.max(max,middleHeight);
}
return max;
}; | 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 squares, never on filled ones.
The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return "Draw". If there are still movements to play return "Pending".
You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.
Example 1:
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: A wins, they always play first.
Example 2:
Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: B wins.
Example 3:
Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
Constraints:
1 <= moves.length <= 9
moves[i].length == 2
0 <= rowi, coli <= 2
There are no repeated elements on moves.
moves follow the rules of tic tac toe.
| 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)],
[(0, 0), (1, 1), (2, 2)],
[(0, 2), (1, 1), (2, 0)],
]
def checkWin(S):
for win in wins:
flag = True
for pos in win:
if pos not in S:
flag = False
break
if flag:
return True
return False
A, B = set(), set()
for i, (x, y) in enumerate(moves):
if i % 2 == 0:
A.add((x, y))
else:
B.add((x, y))
if checkWin(A):
return 'A'
elif checkWin(B):
return 'B'
return "Draw" if len(moves) == 9 else "Pending" | /**
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++){
int AorB =-1;
if(turn%2==0){AorB=1;}
rcd[0][moves[turn][0]]+= AorB;
rcd[1][moves[turn][1]]+= AorB;
if(moves[turn][0]== moves[turn][1]){rcd[2][0]+=AorB;} // first diagonal
if(moves[turn][0]+moves[turn][1]-2 == 0){rcd[2][1]+=AorB;} //2nd diagonal
if( Math.abs(rcd[0][moves[turn][0]]) == 3 || Math.abs(rcd[1][moves[turn][1]]) == 3
||Math.abs(rcd[2][0]) ==3 || Math.abs(rcd[2][1]) ==3 ){
return AorB == 1 ? "A" : "B"; }
}
return moves.length == 9 ? "Draw" : "Pending";
}
} | 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++){
//check row
if (grid[i][0] == 'x' && grid[i][1] == 'x' && grid[i][2] == 'x')return "A";
if (grid[i][0] == 'o' && grid[i][1] == 'o' && grid[i][2] == 'o')return "B";
//check columns
if (grid[0][i] == 'x' && grid[1][i] == 'x' && grid[2][i] == 'x')return "A";
if (grid[0][i] == 'o' && grid[1][i] == 'o' && grid[2][i] == 'o')return "B";
}
//check diagonal
if (grid[0][0] == 'x' && grid[1][1] == 'x' && grid[2][2] == 'x')return "A";
if (grid[0][2] == 'x' && grid[1][1] == 'x' && grid[2][0] == 'x')return "A";
if (grid[0][0] == 'o' && grid[1][1] == 'o' && grid[2][2] == 'o')return "B";
if (grid[0][2] == 'o' && grid[1][1] == 'o' && grid[2][0] == 'o')return "B";
if(moves.size()==9)
{
return "Draw";
}
return "Pending";
}
};
//if you like the solution plz upvote. | /**
* @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 == 1) ? -1 : 1;
if(validate(grid[x])
|| validate(grid.reduce((prev, curr) => [...prev, curr[y]], []))
|| validate([grid[0][0], grid[1][1], grid[2][2]])
|| validate([grid[0][2], grid[1][1], grid[2][0]])
)
return (i % 2) ? "B" : "A";
}
return (moves.length == 9) ? "Draw" : "Pending"
}; | 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 seconds, etc.
You are also given an integer changeTime and an integer numLaps.
The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds.
Return the minimum time to finish the race.
Example 1:
Input: tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4
Output: 21
Explanation:
Lap 1: Start with tire 0 and finish the lap in 2 seconds.
Lap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.
Lap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.
Lap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.
Total time = 2 + 6 + 5 + 2 + 6 = 21 seconds.
The minimum time to complete the race is 21 seconds.
Example 2:
Input: tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5
Output: 25
Explanation:
Lap 1: Start with tire 1 and finish the lap in 2 seconds.
Lap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.
Lap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.
Lap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.
Lap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.
Total time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.
The minimum time to complete the race is 25 seconds.
Constraints:
1 <= tires.length <= 105
tires[i].length == 2
1 <= fi, changeTime <= 105
2 <= ri <= 105
1 <= numLaps <= 1000
| 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(laps-1)+dp(1) + dp(laps-2)+dp(2) + ...)
# we don't want to use tires too many laps, which will create unrealistic single lap time
# we can evaluate single lap time by using changeTime <= 100000 and r >= 2
# x = minimal continously laps
# single lap time = 1*2^x <= 100000 -> x can't go more than 19
limit = 19
tires = list(set([(t1, t2) for t1, t2 in tires]))
memo = [[(-1,-1) for _ in range(min(limit,numLaps)+1)] for _ in range(len(tires))]
for i in range(len(tires)):
for j in range(1, min(limit,numLaps)+1): # lap 1 to numLaps
if j == 1:
memo[i][j] = (tires[i][0], tires[i][0]) # total time, lap time
else:
# print('i, j', i, j)
tmp = memo[i][j-1][1]*tires[i][1] # cost of continuously use tire this lap
memo[i][j] = (memo[i][j-1][0]+tmp, tmp)
@cache
def dp(laps):
if laps == 1:
return min(memo[i][1][0] for i in range(len(tires)))
# no change:
best_time = min(memo[i][laps][0] for i in range(len(tires))) if laps <= limit else float('inf')
# change tire:
# e.g. change tire at this lap and see if it'll be faster -> dp(laps-1) + changeTime + dp(1)
# check all previous laps: dp(a) + changeTime + dp(b) until a < b
for j in range(1, laps):
a, b = laps-j, j
if a >= b:
ta = dp(a)
tb = dp(b)
if ta+tb+changeTime < best_time:
best_time = ta+tb+changeTime
return best_time
return dp(numLaps) | 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, minTime);
}
int[] dp = new int[numLaps + 1];
for (int i = 1; i <= numLaps; i++){
dp[i] = minTime[i]; // maxValue for dp[i] is Integer.MAX_VALUE, no need to worry about overflow
for (int j = 1; j < i; j++){
dp[i] = Math.min(dp[i], dp[j] + changeTime + dp[i - j]); // it will never overflow, since dp[j] are far less than Integer.MAX_VALUE
}
}
return dp[numLaps];
}
private void populateMinTime(int[] tire, int[] minTime){
int sum = 0;
int base = tire[0];
int ex = tire[1];
int spent = 1;
for (int i = 1; i < minTime.length; i++){
spent = (i == 1) ? base : spent * ex;
if (spent > changeTime + base){break;} // set boundary
sum += spent;
minTime[i] = Math.min(minTime[i], sum);
}
}
} | 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_change(n, vector<int>(20, 2e9));
for (int i = 0; i < n; i++) {
without_change[i][1] = tires[i][0];
for (int j = 2; j < 20; j++) {
if ((long long)without_change[i][j-1] * tires[i][1] >= 2e9)
break;
without_change[i][j] = without_change[i][j-1] * tires[i][1];
}
// since we define it as the total time, rather than just the time for the j-th lap
// we have to make it prefix sum
for (int j = 2; j < 20; j++) {
if ((long long)without_change[i][j-1] + without_change[i][j] >= 2e9)
break;
without_change[i][j] += without_change[i][j-1];
}
}
// dp[x]: the minimum time to finish x laps
vector<int> dp(numLaps+1, 2e9);
for (int i = 0; i < n; i++) {
dp[1] = min(dp[1], tires[i][0]);
}
for (int x = 1; x <= numLaps; x++) {
if (x < 20) {
// x is small enough, so an optimal solution might never changes tires!
for (int i = 0; i < n; i++) {
dp[x] = min(dp[x], without_change[i][x]);
}
}
for (int j = x-1; j > 0 && j >= x-18; j--) {
dp[x] = min(dp[x], dp[j] + changeTime + dp[x-j]);
}
}
return dp[numLaps];
}
}; | 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 cost to complete lap i using same tire
const sameTire = Array(maxSameTire + 1).fill(Infinity)
for (let lap = 1; lap <= maxSameTire; lap++) {
tires.forEach((tire, i) => {
sameTireLast[i] += tire[0] * tire[1] ** (lap - 1)
sameTire[lap] = Math.min(sameTire[lap], sameTireLast[i])
})
}
const dp = Array(numLaps + 1).fill(Infinity)
for (let i = 1; i < numLaps + 1; i++) {
if (i <= maxSameTire) dp[i] = sameTire[i]
// at each lap, we can either use the same tire up to this lap (sameTire[i])
// or a combination of 2 different best times,
// eg lap 6: use best time from lap 3 + lap 3
// or from lap 4 + lap 2
// or lap 5 + lap 1
for (let j = 1; j < i / 2 + 1; j++) {
dp[i] = Math.min(dp[i], dp[i-j] + changeTime + dp[j])
}
}
return dp[numLaps]
}; | 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 values and that we only use the node numbers in this problem.
Example 1:
Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
Output: true
Example 2:
Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
Output: false
Example 3:
Input: n = 2, leftChild = [1,0], rightChild = [-1,-1]
Output: false
Constraints:
n == leftChild.length == rightChild.length
1 <= n <= 104
-1 <= leftChild[i], rightChild[i] <= n - 1
| 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(i)
if len(que)>1 or len(que)==0:
return False
graph=defaultdict(list)
for i in range(n):
graph[i]=[]
if leftChild[i]!=-1:
graph[i].append(leftChild[i])
if rightChild[i]!=-1:
graph[i].append(rightChild[i])
visited=set()
visited.add(que[0])
while len(que)>0:
item=que.pop(0)
children=graph[item]
for child in children:
if child not in visited:
que.append(child)
visited.add(child)
else:
return False
for i in range(n):
if i not in visited:
return False
return True | 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]);
}
boolean union(int a, int b) {
int pA = find(a), pB = find(b);
if (pA == pB) {
return false;
}
parents[pA] = pB;
size--;
return true;
}
boolean connected() {
return size == 1;
}
}
public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
UF uf = new UF(n);
int[] indeg = new int[n];
for (int i = 0; i < n; i++) {
int l = leftChild[i], r = rightChild[i];
if (l != -1) {
/**
* i: parent node
* l: left child node
* if i and l are already connected or the in degree of l is already 1
*/
if (!uf.union(i, l) || ++indeg[l] > 1) {
return false;
}
}
if (r != -1) {
// Same thing for parent node and the right child node
if (!uf.union(i, r) || ++indeg[r] > 1) {
return false;
}
}
}
return uf.connected();
}
} | 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<n;i++){
parent[i]=i;
}
int cnt=0;
for(int i=0;i<n;i++){
int y=find_parent(parent,i);
if(leftChild[i]!=-1){
int x=find_parent(parent,leftChild[i]);
if(x!=leftChild[i]||y==x)
return false;
parent[leftChild[i]]=y;
}
if(rightChild[i]!=-1){
int x=find_parent(parent,rightChild[i]);
if(x!=rightChild[i]||y==x)
return false;
parent[rightChild[i]]=y;
}
}
int x=find_parent(parent,0);
for(int i=1;i<n;i++){
if(find_parent(parent,i)!=x)
return false;
}
return true;
}
}; | 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[rightChild[i]];
}
}
// find the root node and check each node has only one in-degree
let rootNodeId = -1;
for(let i = 0; i < n; ++i) {
if(inDeg[i] === 0) {
rootNodeId = i;
} else if(inDeg[i] > 1) {
return false;
}
}
// if no root node found -> invalid BT
if(rootNodeId === -1) {
return false;
}
// BFS to check that each node is visited at least and at most once
const visited = new Set();
const queue = [rootNodeId];
while(queue.length) {
const nodeId = queue.shift();
if(visited.has(nodeId)) {
return false;
}
visited.add(nodeId);
const leftNode = leftChild[nodeId],
rightNode = rightChild[nodeId];
if(leftNode !== -1) {
queue.push(leftNode);
}
if(rightNode !== -1) {
queue.push(rightNode);
}
}
// checking each node is visited at least once
return visited.size === n;}; | 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 value in nums strictly smaller than largest. Let its value be nextLargest.
Reduce nums[i] to nextLargest.
Return the number of operations to make all elements in nums equal.
Example 1:
Input: nums = [5,1,3]
Output: 3
Explanation: It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].
Example 2:
Input: nums = [1,1,1]
Output: 0
Explanation: All elements in nums are already equal.
Example 3:
Input: nums = [1,1,2,2,3]
Output: 4
Explanation: It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].
Constraints:
1 <= nums.length <= 5 * 104
1 <= nums[i] <= 5 * 104
| 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 = 0;
for (Map.Entry<Integer, Integer> entry : valMap.entrySet()) {
opsCount += entry.getValue() * (--mapSize);
}
return 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 i = mp.end(); i != mp.begin(); i--) {
ans += i -> second + pre; // total operations
pre += i -> second; // maintaing the previous frequency count
}
return ans;
}
}; | /**
* @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 -1.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [0,1,0], k = 1
Output: 2
Explanation: Flip nums[0], then flip nums[2].
Example 2:
Input: nums = [1,1,0], k = 2
Output: -1
Explanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].
Example 3:
Input: nums = [0,0,0,1,0,1,1,0], k = 3
Output: 3
Explanation:
Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]
Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]
Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]
Constraints:
1 <= nums.length <= 105
1 <= k <= nums.length
| 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:
csum -= flips[left-k+1]
for check in range(len(nums)-k+1, len(nums)):
if (nums[check] + csum) % 2 == 0:
return -1
if check >= k-1:
csum -= flips[check-k+1]
return sum(flips) | 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){
target^=1;
flip[i+k]^=true;
ans++;
}
if (i>nums.length-k&&nums[i]==target){
return -1;
}
}
return ans;
}
} | 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; // answer
for(int i=0;i<n;i++){
flips +=flip[i]; // update flips for current position
// even flips on 1 okay
if(nums[i]==1 && (flips)%2==0){
continue;
}
// odd flips on 0 okay
if(nums[i]==0 && (flips)%2!=0){
continue;
}
// margin error as k bits flips is must
if(i+k > n){
return -1;
}
ops++; //increment ans
flips++; // do flip at this position
flip[i+k] = -1; // set poiter where current flip ends
}
return ops;
}
}; | 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) ? count : -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:
MedianFinder() initializes the MedianFinder object.
void addNum(int num) adds the integer num from the data stream to the data structure.
double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]
Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = [1]
medianFinder.addNum(2); // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3); // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0
Constraints:
-105 <= num <= 105
There will be at least one element in the data structure before calling findMedian.
At most 5 * 104 calls will be made to addNum and findMedian.
Follow up:
If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
| 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)
heapq.heappush(self.max_hp, -num)
heapq.heappush(self.min_hp, cur)
else:
heapq.heappush(self.min_hp, num)
else:
if num>self.min_hp[0]:
cur = heapq.heappop(self.min_hp)
heapq.heappush(self.min_hp, num)
heapq.heappush(self.max_hp, -cur)
else:
heapq.heappush(self.max_hp, -num)
def findMedian(self) -> float:
if len(self.min_hp) == len(self.max_hp):
return (self.min_hp[0] + -self.max_hp[0]) /2
else:
return self.min_hp[0] | 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.peek() > num) ){
maxHeap.offer(num);
}
else{
minHeap.offer(num);
}
//Balancing
if ( maxHeap.size() > minHeap.size()+ 1){
minHeap.offer(maxHeap.peek());
maxHeap.poll();
}
else if (minHeap.size() > maxHeap.size()+ 1 ){
maxHeap.offer(minHeap.peek());
minHeap.poll();
}
}
public double findMedian() {
//Evaluating Median
if ( maxHeap.size() == minHeap.size() ){ // Even Number
return ((int)maxHeap.peek()+ (int)minHeap.peek())/2.0;
}
else{ //Odd Number
if ( maxHeap.size() > minHeap.size()){
return (int)maxHeap.peek()+ 0.0;
}
else{ // minHeap.size() > maxHeap.size()
return (int)minHeap.peek()+ 0.0;
}
}
}
} | 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();
while(small.size() < large.size()){
small.push(-large.top());
large.pop();
}
}
double findMedian() {
return small.size() > large.size()
? small.top()
: (small.top() - large.top())/2.0;
}
}; | 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)
} else {
left.enqueue(num)
}
if (Math.abs(left.size() - right.size()) == 2) {
if (left.size() > right.size()) {
right.enqueue(left.dequeue().element)
} else {
left.enqueue(right.dequeue().element)
}
}
};
/**
* @return {number}
*/
MedianFinder.prototype.findMedian = function() {
let { left, right } = this
if (left.size() > right.size()) {
return left.front().element
} else if(right.size() > left.size()) {
return right.front().element
} else{
// get the sum of all
return (left.front().element + right.front().element) / 2
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* var obj = new MedianFinder()
* obj.addNum(num)
* var param_2 = obj.findMedian()
*/ | 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 the format YYYY-MM-DD, where:
YYYY denotes the 4 digit year.
MM denotes the 2 digit month.
DD denotes the 2 digit day.
Example 1:
Input: date = "20th Oct 2052"
Output: "2052-10-20"
Example 2:
Input: date = "6th Jun 1933"
Output: "1933-06-06"
Example 3:
Input: date = "26th May 1960"
Output: "1960-05-26"
Constraints:
The given dates are guaranteed to be valid, so no error handling is necessary.
| 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:] + "-" + m_dict_[date[-8:-5]] + "-" + day) | 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(monthArray).indexOf(date.substring(len - 8, len - 5)) + 1;
String day = date.substring(0, len - 11);
StringBuffer sb = new StringBuffer();
sb.append(year + "-");
if(month < 10)
sb.append("0" + month + "-");
else
sb.append(month + "-");
if(day.length() == 1)
sb.append("0" + day);
else
sb.append(day);
return sb.toString();
}
} | 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"] =11;
m["Dec"] =12;
string ans;
for(int i=date.length()-4; i<date.length(); i++){
ans+=date[i];
}
ans += "-";
string month;
for(int i=date.length()-8; i<=date.length()-6; i++){
month+=date[i];
}
int yes = m[month];
if(yes<=9){
ans += '0';
}
ans = ans + to_string(yes);
ans += "-";
int i = 0;
if(date[1]=='t' || date[1]=='s' || date[1]=='n' || date[1]=='r'){
ans+='0';
ans+=date[0];
}
else{
ans+=date[0];
ans+=date[1];
}
return ans;
}
}; | 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 monthIndex = month.findIndex(mon => mon === inputMonth);
const formatedMonth = String(monthIndex + 1).padStart(2,'0');
ans.push(formatedMonth);
ans.push("-");
const slicedDate = inputDate.slice(0,2);
if(+slicedDate >= 10){
ans.push(slicedDate);
}else{
const formatedDate = inputDate.slice(0,1).padStart(2,'0');
ans.push(formatedDate)
}
return ans.join('');
}; | 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 circumference of a circle are also considered to be inside it.
Example 1:
Input: circles = [[2,2,1]]
Output: 5
Explanation:
The figure above shows the given circle.
The lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.
Other points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.
Hence, the number of lattice points present inside at least one circle is 5.
Example 2:
Input: circles = [[2,2,2],[3,4,1]]
Output: 16
Explanation:
The figure above shows the given circles.
There are exactly 16 lattice points which are present inside at least one circle.
Some of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).
Constraints:
1 <= circles.length <= 200
circles[i].length == 3
1 <= xi, yi <= 100
1 <= ri <= min(xi, yi)
| 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)
return sum(m) | 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 containing the whole circle
for (int xx = x - r; xx <= x + r; xx++)
for (int yy = y - r; yy <= y + r; yy++)
if ((r * r) >= ((x - xx) * (x - xx)) + ((y - yy) * (y - yy)))
answer.add(xx + ":" + yy);
}
return answer.size();
}
} | 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>> set ;
for(auto v : circles){
int r = v[2] , x = v[0] , y = v[1];
for(int i = x-r ; i <= x+r ; i++)
for(int j = y-r ; j <= y+r ; j++)
if(circle(i,j,x,y,r)){
pair<int,int> p(i,j) ;
set.insert(p) ;
}
}
return set.size() ;
}
}; | 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, circles[i][1]+circles[i][2]);
}
let count=0;
for(let i=minX; i<=maxX; i++){
for(let j=minY; j<=maxY; j++){
let find=false;
for(let k=0; k<circles.length; k++){
if(((i-circles[k][0])**2+(j-circles[k][1])**2)<=circles[k][2]**2){
find=true; break;
}
}
if(find){count++};
}
}
return count;
}; | 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 first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person.
This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift).
Return an array (of length num_people and sum candies) that represents the final distribution of candies.
Example 1:
Input: candies = 7, num_people = 4
Output: [1,2,3,1]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0,0].
On the third turn, ans[2] += 3, and the array is [1,2,3,0].
On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].
Example 2:
Input: candies = 10, num_people = 3
Output: [5,2,3]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0].
On the third turn, ans[2] += 3, and the array is [1,2,3].
On the fourth turn, ans[0] += 4, and the final array is [5,2,3].
Constraints:
1 <= candies <= 10^9
1 <= num_people <= 1000
| 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 :
i = 0
if candies - totalCandy >= candy :
candy_dict[i] += candy
totalCandy += candy
else :
candy_dict[i] += candies - totalCandy
totalCandy += candies - totalCandy
i += 1
candy += 1
return candy_dict.values() | 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;
k++;
}
else{
a[i]+=candies;
candies=0;
break;
}
}
}
return a;
}
} | 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 (candies >= Num)
{
Candies[i] += Num;
candies -= Num;
}
else
{
Candies[i] += candies;
candies = 0;
break;
}
}
++X;
}
return Candies;
}
}; | 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_people)
j=0;
i++;
}
return result;
}; | 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 operations.
The function gcd(x, y) is the greatest common divisor of x and y.
Example 1:
Input: nums = [1,2]
Output: 1
Explanation: The optimal choice of operations is:
(1 * gcd(1, 2)) = 1
Example 2:
Input: nums = [3,4,6,8]
Output: 11
Explanation: The optimal choice of operations is:
(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11
Example 3:
Input: nums = [1,2,3,4,5,6]
Output: 14
Explanation: The optimal choice of operations is:
(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14
Constraints:
1 <= n <= 7
nums.length == 2 * n
1 <= nums[i] <= 106
| 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:
return 0
res = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if not(mask & (1<<i)) and not(mask &(1<<j)):
res = max(res, k*gcd(nums[i], nums[j])+dfs(mask|(1<<i)|(1<<j), k+1))
return res
return dfs(0, 1) | 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 = new int[1 << n];
for (int i = 0; i < (1 << n); ++i) {
int bits = Integer.bitCount(i); // how many numbers are used
if (bits % 2 != 0) // odd numbers, skip it
continue;
for (int k : gcdVal.keySet()) {
if ((k & i) != 0) // overlapping used numbers
continue;
dp[i ^ k] = Math.max(dp[i ^ k], dp[i] + gcdVal.get(k) * (bits / 2 + 1));
}
}
return dp[(1 << n) - 1];
}
public int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
}
// Time: O(2^n * n^2)
// Space: O(2 ^ n) | 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[j]);}
}
// Looping from state 0 to (1<<sz)-1
dp[0] = 0;
for (int s = 0; s < (1<<sz); ++s) {
int cnt = __builtin_popcount(s);
if (cnt &1 )continue; // bitcount can't be odd
for (int i = 0; i < sz; ++i) {
if (s & (1<<i)) continue;
for (int j = i+1; j < sz; ++j) {
if (s & (1<<j)) continue;
int next_state = s^(1<<i)^(1<<j);
dp[next_state] = max(dp[next_state], dp[s] + (cnt/2+1)*gcd_table[i][j]);
}
}
}
return dp[(1<<sz)-1];
}
}; | 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.get(key);
let max = 0;
for(let i = 0; i < arr.length; i++) {
const nextArr = [...arr.slice(0, i), ...arr.slice(i+1)];
if(num1) {
const currGCD = gcd(num1, arr[i]);
const rest = recurse(nextArr, null, op+1);
max = Math.max(max, ((op * currGCD) + rest));
} else {
const rest = recurse(nextArr, arr[i], op);
max = Math.max(max, rest);
}
}
memo.set(key, max);
return max;
}
return recurse(nums, null, 1);
}; | 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.
Example 1:
Input: nums = [1,5,0,3,5]
Output: 3
Explanation:
In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].
In the second operation, choose x = 2. Now, nums = [0,2,0,0,2].
In the third operation, choose x = 2. Now, nums = [0,0,0,0,0].
Example 2:
Input: nums = [0]
Output: 0
Explanation: Each element in nums is already 0 so no operations are needed.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
| 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) {
s.remove(0);
}
result = s.size();;
}
return result;
}
} | 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.top()==0)pq.pop();
else{
int top=pq.top()-curr_min;
if(top!=0){
curr_min+=top;
count++;
}
pq.pop();
}
}
return count;
}
}; | 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: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
1 <= num1.length, num2.length <= 200
num1 and num2 consist of digits only.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
| 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
return currNum
n1 = convertToInt(num1)
n2 = convertToInt(num2)
return str(n1 * n2)
| 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 column=0;
for(int j=num2.length()-1;j>=0;j--)
{
int a=(num1.charAt(i)-'0')*(num2.charAt(j)-'0');
int temp=(arr[index+column]+carry+a);
arr[index+column]=temp%10;
carry=temp/10;
column++;
}
if(carry!=0)
{
arr[index+column]=carry;
}
index++;
}
String ans="";
index=arr.length-1;
while(arr[index]==0)
{
index--;
}
for(int i=index;i>=0;i--)
{
ans+=arr[i];
}
return ans;
}
} | 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/10; // carry update..
mul %= 10; // mul update in a single digit..
if(ind >= ans.length()){ // here if the index where we'll put the value is out of bounds...
ans.push_back('0' + mul);
}
else{
// here adding the val with the previous digit and further computing the carry...
mul += (ans[ind] - '0');
c += mul/10;
mul %= 10;
ans[ind] = ('0' + mul);
}
i--;
ind++; // increment the index where we'll put the val;
}
if(c > 0){ // if carry is non-zero...
ans.push_back('0' + c);
}
}
public:
string multiply(string num1, string num2) {
string ans = ""; // the string which we have to return as answer..
if(num1 == "0" || num2 == "0") return "0"; // base case..
int ind = 0; // the index from which we'll add the multiplied value to the ans string
for(int i = num1.size()-1; i >= 0; ind++,i--){
// travarsing in reverse dir. on num1 and increasing ind bcz for every digit
// of num1 we'll add the multiplication in a index greater than the previous iteration
int dig = num1[i]-'0'; // the digit with which we'll multiply by num2..
compute(num2, dig, ind, ans); // function call for every digit and num2
}
// we have calculated the ans in a reverse way such that we can easily add a leading digit & now reversing it...
reverse(ans.begin(), ans.end());
return ans;
}
}; | 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 -= 1) {
const digitTwo = parseInt(num2[j]);
const product = digitOne * digitTwo + carry;
const newDigit = product % 10;
carry = Math.floor(product / 10);
step = newDigit + step;
}
if(carry > 0) step = carry + step;
steps.push(step);
}
for(let i = 0; i < steps.length - 1; i += 1) {
let nextStep = steps[i + 1];
let step = steps[i];
step = "0".repeat(nextStep.length - step.length) + step;
carry = 0;
let newStep = "";
for(let j = step.length - 1; j >= 0; j -= 1) {
const sum = parseInt(nextStep[j]) + parseInt(step[j]) + carry;
const digit = sum % 10;
carry = Math.floor(sum / 10);
newStep = digit + newStep;
}
if(carry > 0) newStep = carry + newStep;
steps[i + 1] = newStep;
}
let result = steps[steps.length - 1];
let leadingZeros = 0
while(leadingZeros < result.length - 1 && result[leadingZeros] === '0') {
leadingZeros += 1;
}
return result.slice(leadingZeros);
}; | 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 distance between them.
Return the maximum score of a pair of sightseeing spots.
Example 1:
Input: values = [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
Example 2:
Input: values = [1,2]
Output: 2
Constraints:
2 <= values.length <= 5 * 104
1 <= values[i] <= 1000
| 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, 0, 0]
max_val[i] = max(max_val[i-1]-1, values[i-1]-1)
we have to do it once from left side and then from right side
"""
def maxScoreSightseeingPair(self, values: List[int]) -> int:
left_max_vals = [float('-inf') for _ in range(len(values))]
right_max_vals = [float('-inf') for _ in range(len(values))]
for i in range(1, len(values)):
left_max_vals[i] = max(left_max_vals[i-1]-1, values[i-1]-1)
for i in range(len(values)-2, -1, -1):
right_max_vals[i] = max(right_max_vals[i+1]-1, values[i+1]-1)
max_pair = float('-inf')
for i in range(len(values)):
max_pair = max(max_pair, values[i] + max(left_max_vals[i], right_max_vals[i]))
return max_pair | 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);
}
return ans;
}
} | 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 curIndexMaxValue=values[i]+prevIndexMaxAddition-1;
if(maxValue<curIndexMaxValue){
maxValue=curIndexMaxValue;
}
prevIndexMaxAddition=curIndexMaxAddition;
}
return maxValue;
}; | 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 if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.
Example 1:
Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
Example 2:
Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false
Example 3:
Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]
Output: false
Constraints:
rec1.length == 4
rec2.length == 4
-109 <= rec1[i], rec2[i] <= 109
rec1 and rec2 represent a valid rectangle with a non-zero area.
| 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];
int x4 = rec2[2];
int y4 = rec2[3];
if (x1 >= x4 || x2 <= x3 || y1 >= y4 || y2 <= y3) {
return false;
}
return true;
}
} | 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];
int x5 = max(ax1,bx1);
int y5 = max(ay1,by1);
int x6 = min(ax2,bx2);
int y6 = min(ay2,by2);
if(x5<x6 && y5<y6){
return true;
}
else{
return false;
}
}
}; | /**
* @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 = "0090089" can be split into ["0090", "089"] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid.
Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or ["0", "0", "1"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.
Return true if it is possible to split s as described above, or false otherwise.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "1234"
Output: false
Explanation: There is no valid way to split s.
Example 2:
Input: s = "050043"
Output: true
Explanation: s can be split into ["05", "004", "3"] with numerical values [5,4,3].
The values are in descending order with adjacent values differing by 1.
Example 3:
Input: s = "9080701"
Output: false
Explanation: There is no valid way to split s.
Constraints:
1 <= s.length <= 20
s only consists of digits.
| 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 = int(s[:i])
# If current slice is equal to last_val - 1, make
# recursive call with remaining string and updated last_val
if last_val is None or cur == last_val - 1:
if self.splitString(s[i:], cur):
return True
return False | 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 >= 10000000000L) return false; // Avoid overflow
if(previous == null) {
if (isRemainingValid(s.substring(i+1), current))
return true;
} else if(current == previous - 1 && (i==s.length()-1 || isRemainingValid(s.substring(i+1), current)))
return true;
}
return false;
}
} | 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;
}
return false;
}
public:
bool splitString(string s) {
for (int i = 1; i < s.size(); ++i) {
long long int tar = stoull(s.substr(0, i));
if (helper(s.substr(i, s.size()-i), tar-1))
return true;
}
return false;
}
}; | /**
* @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);
if(parseInt(prevStringValue, 10) === parseInt(currStringValue, 10) + 1) {
if(backtracking(i + 1, currStringValue)) {
return true;
}
}
}
}
// we need to have at least two values to compare, so we start with the for outside the backtracking function
for (let i = 1; i <= s.length - 1; i++) {
const currStringValue = s.slice(0, i);
if (backtracking(i, currStringValue)) {
return true;
}
}
return false
}; | 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],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
-109 <= matrix[i][j] <= 109
| 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];
}
}
return trans;
}
} | 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_back(v[j]);
}
}
for(auto i:m){
result.push_back(i.second);
}
return result;
}
}; | 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 ] , [ 7 , 8 , 9 ] ] ) ) | 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: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Constraints:
The number of the nodes in the given list is in the range [2, 1000].
-1000 <= Node.val <= 1000
The value of each node in the list is unique.
The node to be deleted is in the list and is not a tail node
| # 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.val
node.next = node.next.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.next;
// 4 1 9
}
} | /**
* 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;
ListNode* delNode = node->next;
node->next = node->next->next;
delete delNode;
}
}; | 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, to produce a multilevel data structure as shown in the example below.
Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.
Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.
Example 1:
Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Output: [1,2,3,7,8,11,12,9,10,4,5,6]
Explanation: The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
Example 2:
Input: head = [1,2,null,3]
Output: [1,3,2]
Explanation: The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
Example 3:
Input: head = []
Output: []
Explanation: There could be empty list in the input.
Constraints:
The number of Nodes will not exceed 1000.
1 <= Node.val <= 105
How the multilevel linked list is represented in test cases:
We use the multilevel linked list from Example 1 above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
[1,2,3,4,5,6,null]
[7,8,9,10,null]
[11,12,null]
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
[1, 2, 3, 4, 5, 6, null]
|
[null, null, 7, 8, 9, 10, null]
|
[ null, 11, 12, null]
Merging the serialization of each level and removing trailing nulls we obtain:
[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
| """
# 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:
if node.child: # If there is a child travel to last node of the child
child = node.child
while child.next:
child = child.next
child.next = node.next # Update the next of child to the the next of the current node
if node.next: # update the prev of the next node to chile to make it valid doubly linked list
node.next.prev = child
node.next = node.child # Update the child to become the next of the current
node.next.prev = node # update the prev of the next node to chile to make it valid doubly linked list
node.child = None # Make the child of the current node None to fulfill the requirements
node = node.next
return head
# time and space complexity
# time: O(n)
# space: O(1) | 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){
if(curr.child != null){ // if there is a child
Node child = curr.child; // creating a node for child
if(curr.next != null){ // if there is list after we find child a child
stack.push(curr.next); // pushing the list to the stack
curr.next.prev = null; // pointing its previous to null
}
curr.next = child; // pointing the current's reference to child
child.prev = curr; // pointing child's previous reference to current.
curr.child = null; // pointing the current's child pointer to null
}
tail = curr ; // for keeping track of previous nodes
curr= curr.next; // traversing
}
while(!stack.isEmpty()){ // checking if the stack has still nodes in it.
curr = stack.pop(); // getting the last node of the list pushed into the stack
tail.next = curr; // pointing the previos node to the last node
curr.prev = tail; // pointing previos pointer of the last node to the previos node.
while( curr != null){ // traversing the last node's popped out of stack
tail = curr;
curr = curr.next ;
}
}
return head;
}
} | 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())
{
Node *a=stk.top();
stk.pop();
temp->next=a;
a->prev=temp;
}
if(temp->child!=NULL)
{
if(temp->next!=NULL)
{
Node* a=temp->next;
a->prev=NULL;
stk.push(a);
}
temp->next=temp->child;
temp->next->prev=temp;
temp->child=NULL;
}
temp=temp->next;
}
return head;
}
};
Feel free to ask in doubt in comment section | 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;
temp.child = null;
}
prev = temp;
temp = temp.next
}
for(var j=arr.length-1; j>=0; j--)
{
if(arr[j] != null)
mergeOtherLists(arr[j]);
}
return head;
function mergeOtherLists(root)
{
prev.next=root;
root.prev=prev;
while(root)
{
prev = root;
root = root.next;
}
}
}; | 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 only lucky number since it is the minimum in its row and the maximum in its column.
Example 2:
Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
Example 3:
Input: matrix = [[7,8],[1,2]]
Output: [7]
Explanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
Constraints:
m == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 105.
All elements in the matrix are distinct.
| 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:
for i in range(n):
max_check = []
for j in range(m):
max_check.append(matrix[j][i])
max_temp.append(max(max_check))
return set(min_temp).intersection(set(max_temp))
elif n == 1:
for i in range(m):
max_check = []
for j in range(n):
max_check.append(matrix[i][j])
max_temp.append(max(max_check))
return [max(max_temp)]
else:
for i in range(n):
max_check = []
for j in range(m):
max_check.append(matrix[j][i])
max_temp.append(max(max_check))
return set(min_temp).intersection(set(max_temp)) | 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 = true;
for(int col = 0; col < m; col++){
if(min > row[col]){
min = row[col];
index = col;
}
}
for(int r = 0; r < n; r++){
if(min < matrix[r][index]){
lucky = false;
break;
}
}
if(lucky){
luckyNums.add(min);
}
}
return luckyNums;
}
} | 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]);
}
}
unordered_map<int,int>mp;
for(int i=0;i<matrix.size();i++){
vector<int>helper = matrix[i];
sort(helper.begin(),helper.end());
mp[helper[0]]++;
}
vector<int>result;
for(auto i:m){
vector<int>helper = i.second;
sort(helper.begin(),helper.end());
int a = helper[helper.size()-1];
if(mp.find(a)!=mp.end()){
result.push_back(a);
}
}
return result;
}
}; | /**
* @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.min(...row));
// build columns
for (let j = 0; j < row.length; j++) {
cols[j].push(row[j]);
}
}
// Compare sets
for (const col of cols)
colLucky.add(Math.max(...col));
return [...rowLucky].filter(x => colLucky.has(x));
}; | 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 apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks).
Return an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied.
Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.
Example 1:
Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]
Output: [2]
Explanation: Starting with the grid:
[[1,0,0,0],
[1,1,1,0]]
We erase the underlined brick at (1,0), resulting in the grid:
[[1,0,0,0],
[0,1,1,0]]
The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:
[[1,0,0,0],
[0,0,0,0]]
Hence the result is [2].
Example 2:
Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]
Output: [0,0]
Explanation: Starting with the grid:
[[1,0,0,0],
[1,1,0,0]]
We erase the underlined brick at (1,1), resulting in the grid:
[[1,0,0,0],
[1,0,0,0]]
All remaining bricks are still stable, so no bricks fall. The grid remains the same:
[[1,0,0,0],
[1,0,0,0]]
Next, we erase the underlined brick at (1,0), resulting in the grid:
[[1,0,0,0],
[0,0,0,0]]
Once again, all remaining bricks are still stable, so no bricks fall.
Hence the result is [0,0].
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
grid[i][j] is 0 or 1.
1 <= hits.length <= 4 * 104
hits[i].length == 2
0 <= xi <= m - 1
0 <= yi <= n - 1
All (xi, yi) are unique.
| 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])
return parent[i]
def union(i,j):
pi = find(i)
pj = find(j)
if pi != pj:
parent[pi] = pj
sz[pj] += sz[pi]
row = len(grid)
col = len(grid[0])
for r in range(row):
for c in range(col):
parent[(r,c)] = (r,c)
parent[(row,col)] = (row,col)
for r, c in hits:
if grid[r][c]:
grid[r][c] = 0
else:
empty.add((r,c))
for r in range(row):
for c in range(col):
if not grid[r][c]:
continue
for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:
if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:
union((r, c),(r+dr, c+dc))
if r == 0:
union((r,c),(row,col))
res = [0]*len(hits)
for i in range(len(hits)-1,-1,-1):
r, c = hits[i]
if (r,c) in empty:
continue
grid[r][c] = 1
curbricks = sz[find((row,col))]
for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:
if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:
union((r,c),(r+dr,c+dc))
if r == 0:
union((r,c),(row,col))
nextbricks = sz[find((row,col))]
if nextbricks > curbricks:
res[i] = nextbricks - curbricks - 1
return res | 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][1]] = -1;
//marking all the stable bricks
for(int i=0;i<grid[0].length;i++)
markAndCountStableBricks(grid, 0, i);
int[] res = new int[hits.length];
//looping over hits array backwards and restoring bricks
for(int i=hits.length-1;i>=0;i--){
int row = hits[i][0];
int col = hits[i][1];
//hit is at empty space so continue
if(grid[row][col] == 0)
continue;
//marking it with 1, this signifies that a brick is present in an unstable state and will be restored in the future
grid[row][col] = 1;
// checking brick stability, if it's unstable no need to visit the neighbours
if(!isStable(grid, row, col))
continue;
//So now as our brick is stable we can restore all the bricks connected to it
//mark all the unstable bricks as stable and get the count
res[i] = markAndCountStableBricks(grid, hits[i][0], hits[i][1])-1; //Subtracting 1 from the total count, as we don't wanna include the starting restored brick
}
return res;
}
private int markAndCountStableBricks(int[][] grid, int row, int col){
if(grid[row][col] == 0 || grid[row][col] == -1)
return 0;
grid[row][col] = 2;
int stableBricks = 1;
for(int[] dir:dirs){
int r = row+dir[0];
int c = col+dir[1];
if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)
continue;
if(grid[r][c] == 0 || grid[r][c] == -1 || grid[r][c] == 2)
continue;
stableBricks += markAndCountStableBricks(grid, r, c);
}
return stableBricks;
}
private boolean isStable(int[][] grid, int row, int col){
if(row == 0)
return true;
for(int[] dir:dirs){
int r = row+dir[0];
int c = col+dir[1];
if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)
continue;
if(grid[r][c] == 2)
return true;
}
return false;
}
} | 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])
return true;
if(i<vis.size()-1 && vis[i+1][j])
return true;
if(j<vis[0].size()-1 && vis[i][j+1])
return true;
return false;
}
vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) {
vector<int> ans(hits.size(), 0);
//Remove all the bricks which are hit during entire process
vector<vector<int>> mat = grid;
for(int i=0; i<hits.size(); i++)
mat[hits[i][0]][hits[i][1]] = 0;
//Do BFS to determine connected nodes (to top of matrix) and mark them as visited
vector<vector<bool>> vis(grid.size(), vector<bool> (grid[0].size(), false));
queue<pair<int, int>> q;
for(int i=0; i<grid[0].size(); i++){
if(mat[0][i]==1){
vis[0][i] = true;
q.push({0, i});
}
}
while(!q.empty()){
int idx = q.front().first, jdx = q.front().second;
q.pop();
if(idx>0 && mat[idx-1][jdx]==1){
if(!vis[idx-1][jdx])
q.push({idx-1, jdx});
vis[idx-1][jdx]=true;
}
if(jdx>0 && mat[idx][jdx-1]==1){
if(!vis[idx][jdx-1])
q.push({idx, jdx-1});
vis[idx][jdx-1]=true;
}
if(idx<grid.size()-1 && mat[idx+1][jdx]==1){
if(!vis[idx+1][jdx])
q.push({idx+1, jdx});
vis[idx+1][jdx]=true;
}
if(jdx<grid[0].size()-1 && mat[idx][jdx+1]==1){
if(!vis[idx][jdx+1])
q.push({idx, jdx+1});
vis[idx][jdx+1]=true;
}
}
//Traverse the hits array in reverse order to one by one add a brick
for(int i=hits.size()-1; i>=0; i--){
//If no brick was present in original grid matrix, continue, otherwise
//add brick to that position
if(grid[hits[i][0]][hits[i][1]]==0)
continue;
mat[hits[i][0]][hits[i][1]] = 1;
//If this brick not connected to top of matrix, ans=0 and continue
if(!isConnected(vis, hits[i][0], hits[i][1]))
continue;
//This brick connects between visited nodes and not visited nodes, do BFS
//to make all reachable nodes visited and count them
q.push({hits[i][0], hits[i][1]});
vis[hits[i][0]][hits[i][1]] = true;
int cnt=0;
while(!q.empty()){
int idx = q.front().first, jdx = q.front().second;
q.pop();
cnt++;
if(idx>0 && mat[idx-1][jdx]==1 && !vis[idx-1][jdx]){
q.push({idx-1, jdx});
vis[idx-1][jdx]=true;
}
if(jdx>0 && mat[idx][jdx-1]==1 && !vis[idx][jdx-1]){
q.push({idx, jdx-1});
vis[idx][jdx-1]=true;
}
if(idx<grid.size()-1 && mat[idx+1][jdx]==1 && !vis[idx+1][jdx]){
q.push({idx+1, jdx});
vis[idx+1][jdx]=true;
}
if(jdx<grid[0].size()-1 && mat[idx][jdx+1]==1 && !vis[idx][jdx+1]){
q.push({idx, jdx+1});
vis[idx][jdx+1]=true;
}
}
ans[i] = cnt-1;
}
return ans;
}
}; | 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++) {
if (grid[0][j] == 1) {
dfs (grid, output, map, 0, j);
break;
}
}
/* removing bricks that are not connected and adding the count to array */
removeBricks(grid, map, output);
} else {
output.push(0)
}
}
return output;
};
function dfs(grid, output, map, i, j) {
if (i >= grid.length || j >= grid[0].length || i < 0 || j < 0) return;
let key = i +'_'+ j
if (map[key]) return;
if (grid[i][j] == 1) {
map[key] = 1;
dfs(grid, output, map, i+1, j);
dfs(grid, output, map, i-1, j);
dfs(grid, output, map, i, j+1);
dfs(grid, output, map, i, j-1);
}
}
function removeBricks (grid, map, output) {
let count = 0;
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
let key = row +'_'+ col;
if (grid[row][col] == 1 && !map[key] ) {
grid[row][col] = 0;
count++
}
}
}
output.push(count)
} | 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.0" are valid IPv4 addresses while "192.168.01.1", "192.168.1.00", and "[email protected]" are invalid IPv4 addresses.
A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8" where:
1 <= xi.length <= 4
xi is a hexadecimal string which may contain digits, lowercase English letter ('a' to 'f') and upper-case English letters ('A' to 'F').
Leading zeros are allowed in xi.
For example, "2001:0db8:85a3:0000:0000:8a2e:0370:7334" and "2001:db8:85a3:0:0:8A2E:0370:7334" are valid IPv6 addresses, while "2001:0db8:85a3::8A2E:037j:7334" and "02001:0db8:85a3:0000:0000:8a2e:0370:7334" are invalid IPv6 addresses.
Example 1:
Input: queryIP = "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".
Example 2:
Input: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Explanation: This is a valid IPv6 address, return "IPv6".
Example 3:
Input: queryIP = "256.256.256.256"
Output: "Neither"
Explanation: This is neither a IPv4 address nor a IPv6 address.
Constraints:
queryIP consists only of English letters, digits and the characters '.' and ':'.
| 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 == "":
return "Neither"
if i.isnumeric():
if len(i) > 1:
if i.count('0') == len(i) or int(i) > 255 or i[0] == '0':
return "Neither"
else:
return "Neither"
return "IPv4"
elif ct == 8:
a = ['a','b','c','d','e','f','A','B','C','D','E','F']
for i in queryIP.split(":"):
if i == "":
return "Neither"
if len(i) < 5:
for j in i:
if j not in a and j.isdigit() == False:
return "Neither"
else:
return "Neither"
return "IPv6"
else:
return "Neither"
| 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(queryIP.matches(regexIpv4))
return "IPv4";
else if(queryIP.matches(regexIpv6))
return "IPv6";
else
return "Neither";
}
} | 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];
}
}
store.push_back(s);
if(store.size() != 8){
return false;
}
for(int i=0; i<store.size(); i++){
string s = store[i];
if(s.size() > 4 or s.size() == 0){
return false;
}
for(int j=0; j<s.size(); j++){
if(s[j] >= 'a' and s[j] <= 'f'){
continue;
}
else if(s[j] >= 'A' and s[j] <= 'F'){
continue;
}
else if(s[j] >= '0' and s[j] <= '9'){
continue;
}
else{
return false;
}
}
}
return true;
}
bool checkforIPv4(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];
}
}
store.push_back(s);
if(store.size() != 4){
return false;
}
for(int i=0; i<store.size(); i++){
string s = store[i];
if(s.size() > 3 or s.size() == 0){
return false;
}
int num = 0;
for(int j=0; j<s.size(); j++){
if(s.size() >= 2 and s[0] == '0' and s[1] == '0'){
return false;
}
if(s.size() >= 2 and s[0] == '0' and s[1] != '0'){
return false;
}
if(s[j] >= '0' and s[j] <= '9'){
// Do nothing.
}
else{
return false;
}
num = num*10 + (s[j]-'0');
}
if(num > 255 or num < 0){
return false;
}
}
return true;
}
string validIPAddress(string queryIP) {
bool IPv6 = checkforIPv6(queryIP);
bool IPv4 = checkforIPv4(queryIP);
if(IPv6){
return "IPv6";
}
if(IPv4){
return "IPv4";
}
return "Neither";
}
}; | 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) return null;
}
return 'IPv4';
};
const iPv6 = () => {
const address = queryIP.split(':');
if (address.length !== 8) return null;
const config = '0123456789abcdefABCDEF';
const check = address.every(str => {
if (str === '' || str.length > 4) return false;
for (const s of str) {
if (!config.includes(s)) return false;
}
return true;
});
return check ? 'IPv6' : null;
};
return iPv4() ?? iPv6() ?? 'Neither';
}; | 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
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3] => [2,2,3] => [2,2,2]
Example 2:
Input: nums = [1,10,2,9]
Output: 16
Constraints:
n == nums.length
1 <= nums.length <= 105
-109 <= nums[i] <= 109
| 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(val-median)
return ans
| 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 moves is the same.
*/
while (i < j){
res += nums[j] - nums[i];
i++;
j--;
}
return res;
}; | 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 left or from left to right.
Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return the longest ZigZag path contained in that tree.
Example 1:
Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
Output: 3
Explanation: Longest ZigZag path in blue nodes (right -> left -> right).
Example 2:
Input: root = [1,1,1,null,1,null,null,1,1,null,1]
Output: 4
Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).
Example 3:
Input: root = [1]
Output: 0
Constraints:
The number of nodes in the tree is in the range [1, 5 * 104].
1 <= Node.val <= 100
| 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, leftRight, rightLeft)
return leftRight, rightLeft
helper(root)
return 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 Solution {
static class Pair{
int left=-1;
int right=-1;
int maxLen=0;
}
public int longestZigZag(TreeNode root) {
Pair ans=longestZigZag_(root);
return ans.maxLen;
}
public Pair longestZigZag_(TreeNode root) {
if(root==null)
return new Pair();
Pair l=longestZigZag_(root.left);
Pair r=longestZigZag_(root.right);
Pair myAns=new Pair();
myAns.left=l.right+1;
myAns.right=r.left+1;
int max=Math.max(myAns.left,myAns.right);
myAns.maxLen=Math.max(max,Math.max(l.maxLen,r.maxLen));
return myAns;
}
} | 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;
}
int longestZigZag(TreeNode* root) {
func(root);
return ans;
}
}; | /** 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)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var longestZigZag = function(root) {
this.out = 0;
// Recursive left and right node and find the largest height
let left = dfs(root.left, false) + 1;
let right = dfs(root.right, true) + 1;
this.out = Math.max(this.out, Math.max(left, right));
return this.out;
};
var dfs = function(node, isLeft) {
// Node is null, we return -1 because the caller will add 1, so result in 0 (no node visited)
if (node == null) {
return -1;
}
// No left or right node, we return 0 because the caller will add 1, so result in 1 (visited 1 node - this one)
if (node.left == null && node.right == null) {
return 0;
}
// Recursive to see which one is higher, zigzag to left or zigzag to right
let left = dfs(node.left, false) + 1;
let right = dfs(node.right, true) + 1;
this.out = Math.max(this.out, Math.max(left, right));
return isLeft === true ? left : 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 sign, the order in which they were present in nums is preserved.
The rearranged array begins with a positive integer.
Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
Example 1:
Input: nums = [3,1,-2,-5,2,-4]
Output: [3,-2,1,-5,2,-4]
Explanation:
The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.
Example 2:
Input: nums = [-1,1]
Output: [1,-1]
Explanation:
1 is the only positive integer and -1 the only negative integer in nums.
So nums is rearranged to [1,-1].
Constraints:
2 <= nums.length <= 2 * 105
nums.length is even
1 <= |nums[i]| <= 105
nums consists of equal number of positive and negative integers.
| 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 )posIdx++;
res[resIdx++] = nums[posIdx];
}
else{
minusIdx++;
while(nums[minusIdx] > 0 )minusIdx++;
res[resIdx++] = nums[minusIdx];
}
}
return res;
}
} | 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_n = nums.size();
constexpr int kPadPositive = 100006;
constexpr int kPadNegative = -100006;
// Pad the array to have size of a multiple of 4 * chunk_size
for (int i=0; i<nums.size() % (4 * chunk_size); ++i) {
nums.push_back(i % 2 == 0 ? kPadPositive : kPadNegative);
}
ENABLE_LOG(
cout << "chunk_size: " << chunk_size << endl;
cout << "padded array: ";
for (int v: nums) cout << v << " "; cout << endl;
)
// Denotion:
// the i-th positive number in original array: P_i.
// the i-th negative number in original array: N_i
// Step 1: Sort each chunk stably so that positive numbers appear before
// negative numbers
vector<int> chunk_buffer(chunk_size); // stores sorted result
for (int i=0; i < nums.size(); i += chunk_size) {
chunk_buffer.clear();
for (int j=i; j<i+chunk_size; ++j)
if (nums[j] > 0)
chunk_buffer.push_back(nums[j]);
for (int j=i; j<i+chunk_size; ++j)
if (nums[j] < 0)
chunk_buffer.push_back(nums[j]);
// Copy chunk_buffer back to nums[i:i+chunk_size]
copy_n(chunk_buffer.cbegin(), chunk_size, nums.begin() + i);
}
ENABLE_LOG(
cout << "chunk-sorted array: ";
for (int v: nums) cout << v << " "; cout << endl;
)
// Step 2: Merge every two chunks so that each chunk are either all positive numbers
// or all negative numbers
//
// This is based on the observation that:
// assuming chunk A having m positives followed by n negatives,
// chunk B having p positives followed by q negatives,
// a) if m+p >= chunk_size, we extract chunk_size positives into an all-positive chunk and put the remaining (m+p-chunk_size positives and n+q negatives) into the "buffer" chunk
// b) if n+q >= chunk_size, we extract chunk_size negatives into an all-negative chunk and make the remaining (m+p positives and n+q-chunk_size negatives) the "buffer" chunk
// Note that in either of the above two cases, the relative order for positive/negative numbers are unchanged
chunk_buffer = vector<int>{nums.begin(), nums.begin() + chunk_size};
for (int i = chunk_size; i<nums.size(); i+= chunk_size) {
const int m = find_if(chunk_buffer.cbegin(), chunk_buffer.cend(), [](int v) {
return v < 0;
}) - chunk_buffer.cbegin();
const int n = chunk_size - m;
const int p = find_if(nums.cbegin() + i, nums.cbegin() + i + chunk_size, [](int v) {
return v < 0;
}) - (nums.cbegin() + i);
const int q = chunk_size - p;
if (m + p >= chunk_size) {
// Copy positives to the previous chunk
copy_n(chunk_buffer.cbegin(), m, nums.begin() + i - chunk_size);
copy_n(nums.cbegin() + i, chunk_size - m, nums.begin() + i - chunk_size + m);
vector<int> new_buffer;
// the remaining positives (m+p-chunk_size) from this chunk
copy_n(nums.cbegin() + i + (chunk_size - m),
p - (chunk_size - m),
back_inserter(new_buffer));
// the remaining negatives in buffer
copy_n(chunk_buffer.cbegin() + m, n, back_inserter(new_buffer));
// the remaining negatives in this chunk
copy_n(nums.cbegin() + i + p, q, back_inserter(new_buffer));
chunk_buffer = move(new_buffer);
} else {
// Copy negatives to the previous chunk
copy_n(chunk_buffer.cbegin() + m, n, nums.begin() + i - chunk_size);
copy_n(nums.cbegin() + i + p, chunk_size - n, nums.begin() + i - chunk_size + n);
vector<int> new_buffer;
// the remaining positives in buffer
copy_n(chunk_buffer.cbegin(), m, back_inserter(new_buffer));
// the remaining positives in this chunk
copy_n(nums.cbegin() + i, p, back_inserter(new_buffer));
// the remaining negatives from this chunk
copy_n(nums.cbegin() + i + p + chunk_size - n, q - (chunk_size - n),
back_inserter(new_buffer));
chunk_buffer = move(new_buffer);
}
}
copy_n(chunk_buffer.cbegin(), chunk_size, nums.begin() + nums.size() - chunk_size);
ENABLE_LOG(
cout << "homonegeous array: ";
for (int v: nums) cout << v << " "; cout << endl;
)
// Step 3:
// After the above step, we will have sqrt(N) / 2 all-positive chunks and sqrt(N) / 2 all-negative chunks.
// Their initial chunk location is at (0, 1, 2, ..., sqrt(N))
// We want them to interleave each other, i.e., Positive Chunk1, Negative Chunk 1, Positive Chunk 2, Negative Chunk 2
// which could be achieved via cyclic permutation using an additional array tracking the target location of each chunk
// due to above padding, chunk_cnt is always a multiple of 4
const int chunk_cnt = nums.size() / chunk_size;
vector<int> target(chunk_cnt); // O(sqrt(N))
int positive_chunks = 0, negative_chunks = 0;
for (int i=0; i<chunk_cnt; ++i) {
if (nums[i * chunk_size] > 0)
target[i] = (positive_chunks++) * 2;
else
target[i] = (negative_chunks++) * 2 + 1;
}
for (int i=0; i<chunk_cnt; ++i) {
while (target[i] != i) {
swap_ranges(nums.begin() + i * chunk_size,
nums.begin() + i * chunk_size + chunk_size,
nums.begin() + target[i] * chunk_size);
swap(target[target[i]], target[i]);
}
}
ENABLE_LOG(
cout << "sorted array: ";
for (int v: nums) cout << v << " "; cout << endl;
)
// Step 4:
// Now we get Positive Chunk1, Negative Chunk 1, Positive Chunk 2, Negative Chunk 2, ...
// For each pair of adjacent (positive, negative) chunks, we can reorder the elements inside
// to make positive and negative numbers interleave each other
vector<int> two_chunk_elements_interleaved; // O(2 * chunk_size) = O(sqrt(N))
for (int i=0; i<nums.size(); i += 2 * chunk_size) {
two_chunk_elements_interleaved.clear();
for (int j=0; j<chunk_size; ++j)
{
two_chunk_elements_interleaved.push_back(nums[i + j]);
two_chunk_elements_interleaved.push_back(nums[i + chunk_size + j]);
}
copy_n(two_chunk_elements_interleaved.cbegin(), 2 * chunk_size, nums.begin() + i);
}
// Remove paddings
nums.resize(original_n);
return nums;
}
}; | 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;
}
}
return result;
}; | 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{
b--;
}
}
return false;
}
} | 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;
} else if(product>c){
end--;
} else {
start++;
}
}
return false;
}
}; | 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 location of the ith stone, return the largest possible number of stones that can be removed.
Example 1:
Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Explanation: One way to remove 5 stones is as follows:
1. Remove stone [2,2] because it shares the same row as [2,1].
2. Remove stone [2,1] because it shares the same column as [0,1].
3. Remove stone [1,2] because it shares the same row as [1,0].
4. Remove stone [1,0] because it shares the same column as [0,0].
5. Remove stone [0,1] because it shares the same row as [0,0].
Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.
Example 2:
Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
Explanation: One way to make 3 moves is as follows:
1. Remove stone [2,2] because it shares the same row as [2,0].
2. Remove stone [2,0] because it shares the same column as [0,0].
3. Remove stone [0,2] because it shares the same row as [0,0].
Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.
Example 3:
Input: stones = [[0,0]]
Output: 0
Explanation: [0,0] is the only stone on the plane, so you cannot remove it.
Constraints:
1 <= stones.length <= 1000
0 <= xi, yi <= 104
No two stones are at the same coordinate point.
| 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)
return 1
tableRow, tableCol = {},{}
for row,col in stones:
if row not in tableRow:
tableRow[row] = set()
if col not in tableCol:
tableCol[col] = set()
tableRow[row].add((row,col))
tableCol[col].add((row,col))
count,seen= 0, {(row,col):False for row,col in stones}
for row,col in stones:
count += dfs(row,col)
return abs(len(stones)-count) | 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];
if(s1[0]==s2[0] || s1[1]==s2[1]) {
ds.union(i, j);
}
}
}
// System.out.println(Arrays.toString(ds.sets));
for(int i=0;i<ds.sets.length;i++) {
if(ds.sets[i]<0)
ret+=Math.abs(ds.sets[i])-1;
}
return ret;
}
class DisjointSet {
public int sets[];
public DisjointSet(int size) {
sets=new int[size];
Arrays.fill(sets, -1);
}
//
// weighted union
//union->return size in negative
public int union(int idx1, int idx2) {
int p1=find(idx1);
int p2=find(idx2);
if(p1==p2) { //same parent so directly returning size
return sets[p1];
}else {
int w1=Math.abs(sets[p1]);
int w2=Math.abs(sets[p2]);
if(w1>w2) {
sets[p2]=p1;
//collapsing FIND
sets[idx1]=p1;
sets[idx2]=p1;
return sets[p1]=-(w1+w2);
}else {
sets[p1]=p2;
//collapsing FIND
sets[idx1]=p2;
sets[idx2]=p2;
return sets[p2]=-(w1+w2);
}
}
}
// collapsing FIND
//find parent
public int find(int idx) {
int p=idx;
while(sets[p]>=0) {
p=sets[p];
}
return p;
}
}
} | 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;
}
}
int find(int p)
{
while(p!=parent[p])
{
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
bool Union(int p, int q)
{
int rootp = find(p);
int rootq = find(q);
if(rootp == rootq)
return false;
else if(rank[rootp] < rank[rootq])
{
parent[rootp] = rootq;
rank[rootq]++;
count--;
return true;
}
else
{
parent[rootq] = rootp;
rank[rootp]++;
count--;
return true;
}
}
};
public:
int removeStones(vector<vector<int>>& stones) {
int n = stones.size();
UnionFind uf(n);
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
if(stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1])
uf.Union(i,j);
}
}
return n - uf.count;
}
}; | /**
* @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)
// recursively finding the root of rarget node
const find = (a) => {
if(forest[a] === a) {
return a
}
return find(forest[a])
}
// function for uniting two stones
const union = (a, b) => {
const rootA = find(a)
const rootB = find(b)
if(rootA != rootB) {
//connect their roots if currently they are not connected
forest[rootA] = rootB
//subtract the number of islands by one since two islands are connected now
numComponents -= 1
}
}
for(let i = 0; i < stones.length - 1; i++) {
for(let j = i + 1; j < stones.length; j++) {
// if two stones are connected(i.e. share same row or column), unite them
if(stones[i][0] === stones[j][0] || stones[i][1] === stones[j][1]) {
union(i, j)
}
}
}
// this is the most confusing part.
// The number of stones can be removed is not equal to the number of islands.
// e.g. we have two islands with total of 10 stores, each island will leave one extra stone after the
// removal, therefore we can remove 10 - 2 = 8 stones in total
return n - numComponents
}; | 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 && age[x] < 100
Otherwise, x will send a friend request to y.
Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself.
Return the total number of friend requests made.
Example 1:
Input: ages = [16,16]
Output: 2
Explanation: 2 people friend request each other.
Example 2:
Input: ages = [16,17,18]
Output: 2
Explanation: Friend requests are made 17 -> 16, 18 -> 17.
Example 3:
Input: ages = [20,30,100,110,120]
Output: 3
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
Constraints:
n == ages.length
1 <= n <= 2 * 104
1 <= ages[i] <= 120
| 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 that
if current age is x, then valid age group to send a request is:
x*0.5 + 7 < age(y) <= x
we can find the left limit using binary search
"""
def binary_search(self, arr, low, high, value):
if low > high:
return high
mid = (low + high) // 2
if arr[mid] > value:
return self.binary_search(arr, low, mid-1, value)
else:
return self.binary_search(arr, mid+1, high, value)
def numFriendRequests(self, ages: List[int]) -> int:
ages = sorted(ages)
total_count = 0
for i in range(len(ages)-1, -1, -1):
if i+1 < len(ages) and ages[i] == ages[i+1]:
total_count+= prev_count
continue
prev_count = 0
lower_limit = 0.5 * ages[i] + 7
index = self.binary_search(ages, 0, i-1, lower_limit)
prev_count = i - (index+1)
total_count+=prev_count
return total_count | 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;
}
public int numFriendRequests(int[] ages) {
long ans = 0;
Arrays.sort(ages);
// traversing order doesn't matter as we are doing binary-search in whole array
// you can traverse from left side also
for(int i = ages.length - 1;i >= 0;--i){
int k = upperBound(ages,ages[i] / 2 + 7);
int t = upperBound(ages,ages[i]);
ans += Math.max(0,t - k - 1);
}
return (int)ans;
}
} | 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();
int k = upper_bound(ages.begin(), ages.end(), ages[i]) - ages.begin();
sum += max(0, k-j-1);
}
return sum;
}
}; | 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) {
const limit = Math.floor(0.5 * i) + 7;
const rest = tot - count[limit];
res += (count[i] * rest); // current age group send friend request to other people who are within their limit
res += (count[i] * (count[i] - 1)); // current age group send friend request to each other
}
tot += count[i];
count[i] = tot;
}
return res;
}; | 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 again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.
Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.
Return a string of all teams sorted by the ranking system.
Example 1:
Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.
Team B was ranked second by 2 voters and was ranked third by 3 voters.
Team C was ranked second by 3 voters and was ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team and team B is the third.
Example 2:
Input: votes = ["WXYZ","XYZW"]
Output: "XWYZ"
Explanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position.
Example 3:
Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
Explanation: Only one voter so his votes are used for the ranking.
Constraints:
1 <= votes.length <= 1000
1 <= votes[i].length <= 26
votes[i].length == votes[j].length for 0 <= i, j < votes.length.
votes[i][j] is an English uppercase letter.
All characters of votes[i] are unique.
All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length.
| #["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 Solution:
#T=O(mn + mlgm), S=O(mn)
#n=number of votes
#m=number of candidates and m(number of ranks) is constant(26)
def rankTeams(self, votes: List[str]) -> str:
d = {}
#build the dict
#T=O(mn), S=O(mn)
#n=number of votes, m=number of candidates(26)
for vote in votes:
for i, c in enumerate(vote):
#if key not in dict
if c not in d:
#d[char] = [0, 0, 0]
d[c] = [0]*len(vote)
#increment the count of votes for each rank
#d["A"][0] = 1
d[c][i] += 1
#sort the dict keys in ascending order because if there is a tie we return in ascending order
#sorted uses a stable sorting algorithm
#T=O(mlgm), S=O(m)
vote_names = sorted(d.keys()) #d.keys()=["A", "B", "C"]
#sort the dict keys based on votes for each rank in descending order
#T=O(mlgm), S=O(m)
#sorted() always returns a list
vote_rank = sorted(vote_names, reverse=True, key= lambda x: d[x])
#join the list
return "".join(vote_rank) | 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(i);
map.put(team, new int[teams]);
chars.add(team);
}
for(int i = 0 ; i < n ; i++) {
String round = votes[i];
for(int j = 0 ; j < round.length() ; j++) {
map.get(round.charAt(j))[j]+=1;
}
}
chars.sort((a,b) -> {
int[] l1 = map.get(a);
int[] l2 = map.get(b);
for(int i = 0 ; i < l1.length; i++) {
if(l1[i] < l2[i]) {
return 1;
}
else if(l1[i] > l2[i]) {
return -1;
}
}
return a.compareTo(b);
});
StringBuilder sb = new StringBuilder();
for(char c : chars) {
sb.append(c);
}
return sb.toString();
}
} | 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].size();
string ans = "";
vector<vector<int>>vec(noofteams, vector<int>(noofteams+1, 0));
unordered_map<char, int>mp;
for(int i = 0; i<votes[0].size(); i++){
mp[votes[0][i]] = i;
vec[i][0] = votes[0][i]-'a';
}
for(string x: votes){
for(int i = 0; i<x.size(); i++){
vec[mp[x[i]]][i+1]++;
}
}
sort(vec.begin(), vec.end(), cmp);
for(int i = 0; i<vec.size(); i++){
ans.push_back(vec[i][0]+'a');
}
return ans;
}
}; | 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).fill(0))
}
let val = map.get(vote[i])
val[i] = val[i] + 1
map.set(vote[i], val)
}
}
let obj = [...map.entries()]; //converting as array ["A",[5,0,0]]
obj = obj.sort((a,b) => {
for(let i = 0; i < a[1].length;i++){
if(a[1][i] > b[1][i])
return -1;
else if(a[1][i] < b[1][i])
return 1;
}
// if all chars are in same positon return the value charcode
return a[0].charCodeAt(0) - b[0].charCodeAt(0);
})
return obj.map(item => item[0]).join('')
}; | 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 binary tree.
Example 1:
Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [0]
Output: [0]
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100
Follow up: Can you flatten the tree in-place (with O(1) extra space)? | #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 values from left to right
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
prev = None #You can also define that variable inside the init function using self keyword
def dfs(root):
nonlocal prev
if not root:
return
dfs(root.right)
dfs(root.left)
root.right = prev
root.left = None
prev = root
dfs(root)
# If the above solution is hard to understand than one can do level order traversal
#Using Stack DS but this will increase the space complexity to O(N). | 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;
curr.right=curr.left;
curr.left=null;
}
curr=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-place instead.
*/
var flatten = function(root) {
const dfs = (node) => {
if (!node) return
if (!node.left && !node.right) return node
const leftNode = node.left
const rightNode = node.right
const leftTree = dfs(leftNode)
const rightTree = dfs(rightNode)
if (leftTree) leftTree.right = rightNode
node.left = null
node.right = leftNode || rightNode
return rightTree || leftTree
}
dfs(root)
return root
}; | 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 already palindrome we don't need any insertions.
Example 2:
Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".
Example 3:
Input: s = "leetcode"
Output: 5
Explanation: Inserting 5 characters the string becomes "leetcodocteel".
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
| 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:
curr[i] = min(prev[i-1], prev[i])+1
# print(curr)
prev_prev, prev, curr = prev, curr, prev_prev
return prev[-1] | 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,int m,int n){
int [][] t = new int [m+1][n+1];
for(int i=0;i<m+1;i++){
for(int j=0;j<n+1;j++){
if(m==0||n==0){t[m][n]=0;}
}
}
for(int i=1;i<m+1;i++){
for(int j=1;j<n+1;j++){
if(x.charAt(i-1)==y.charAt(j-1)){
t[i][j]=1+t[i-1][j-1];
}
else{t[i][j]=Math.max(t[i][j-1],t[i-1][j]);
}
}
}
return y.length()-t[m][n];
}
} | 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++){
if(x[i-1]==y[j-1])
t[i][j]=1+t[i-1][j-1];
else
t[i][j]=max(t[i-1][j],t[i][j-1]);
}
}
return m-t[m][m];
}
int minInsertions(string s) {
return MinInsertion(s,s.length());
}
}; | 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(i + 1, j - 1);
return dp[i][j] = Math.min(
compute(i + 1, j),
compute(i, j - 1)
) + 1;
}
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 lengths. If two words have the same length, arrange them in their original order.
Return the new text following the format shown above.
Example 1:
Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.
Example 2:
Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.
Example 3:
Input: text = "To be or not to be"
Output: "To be or to be not"
Constraints:
text begins with a capital letter and then contains lowercase letters and single space between words.
1 <= text.length <= 10^5
| 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[0].charAt(0)) + words[0].substring(1);
return String.join(" ", 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 ;
while(iss >> word){
words.push_back({word,pos});
++pos ;
}
//sort by length and pos.
sort(begin(words),end(words),[&](const pair<string,int> &p1 , const pair<string,int> &p2)->bool{
if(size(p1.first) == size(p2.first)) return p1.second < p2.second ;
return size(p1.first) < size(p2.first);
});
string ans = "" ;
for(auto &x : words) ans += x.first + " " ;
ans.pop_back() ;
//convert to uppercase alphabet
ans[0] -= 32 ;
return ans ;
}
}; | 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).
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: 3
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: 5
Constraints:
The total number of nodes is in the range [0, 104].
The depth of the n-ary tree is less than or equal to 1000.
| 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){
return;
}
++depth;
for(Node n:root.children) dfs(n, depth, max);
}
} | 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)
{
mx = max(mx, dep);
}
for(int i = 0 ; i<root->children.size() ; i++)
{
helper(root->children[i], dep+1, mx);
}
}
}; | /**
* // 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(index, max);
if (root?.children && root?.children.length > 0) {
for (let i = 0; i < root.children.length; i++) {
search(root.children[i], index+1);
}
}
}
search(root, 1);
return max;
}; | 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 values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8.
You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.
Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.
Example 1:
Input: n = 3, k = 27
Output: "aay"
Explanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.
Example 2:
Input: n = 5, k = 73
Output: "aaszz"
Constraints:
1 <= n <= 105
n <= k <= 26 * n
| 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 lexicographically smallest string
break
val -= 1 # reduce value by one as we are removing 'a' and replacing by a suitable character
ans[i] = chr(96 + min(k - val, 26)) # replace with a character which is k - value or 'z'
val += ord(ans[i]) - 96 # add the value of newly appended character to value
return ''.join(ans) # return the ans string in the by concatenating the list | 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;
}
return String.valueOf(ch);
}
} | 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[i]='z';
diff-=25;
}else{
str[i]=char('a'+diff);
return str;
}
}
return str;
}
};
// a a a a a
// 5
// diff= 73-5
// | 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:
1 <= nums.length <= 2 * 105
0 <= nums[i] <= 231 - 1
| 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 range(31,-1,-1):
bit = 1 if n&(1<<i) else 0
if bit == 1:
if 0 in cur: cur = cur[0]
else: cur = cur[1]
else:
if 1 in cur: cur = cur[1]
else: cur = cur[0]
ans = max(ans,cur['val']^n)
return ans | 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 {
private static Node root;
public Trie() {
root = new Node();
}
public static void insert(int num) {
Node node = root;
for (int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
if (!node.containsKey(bit)) {
node.put(bit, new Node());
}
node = node.get(bit);
}
}
public static int getMax(int num) {
Node node = root;
int maxNum = 0;
for (int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
if (node.containsKey(1 - bit)) {
maxNum = maxNum | (1 << i);
node = node.get(1 - bit);
}
else {
node = node.get(bit);
}
}
return maxNum;
}
}
class Solution {
public int findMaximumXOR(int[] nums) {
Trie trie = new Trie();
for (int i = 0; i < nums.length; i++) {
trie.insert(nums[i]);
}
int maxi = 0;
for (int i = 0; i < nums.length; i++) {
maxi = Math.max(maxi, trie.getMax(nums[i]));
}
return maxi;
}
} | 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 = (n >> i) & 1; //it will find 31st bit and check it is 1 or 0
if (bit == 0) {
if (curr->zero == nullptr) { //if 0 then we will continue filling on zero side
TrieNode* newNode = new TrieNode();
curr->zero = newNode;
}
curr = curr->zero; //increase cur to next zero position
}
else {
//similarly if we get 1
if (curr->one == nullptr) {
TrieNode* newNode = new TrieNode();
curr->one = newNode;
}
curr = curr->one;
}
}
}
int findmax(TrieNode* root, int n) {
TrieNode* curr = root;
int ans = 0;
for (int i = 31; i >= 0; i--) {
int bit = (n >> i) & 1;
if (bit == 1) {
if (curr->zero != nullptr) { //finding complement , if find 1 then we will check on zero side
ans += (1 << i); //push values in ans
curr = curr->zero;
}
else {
curr = curr->one; //if we don't get then go to one's side
}
}
else {
//similarly on zero side if we get 0 then we will check on 1 s side
if (curr->one != nullptr) {
ans += (1 << i);
curr = curr->one;
}
else {
curr = curr->zero;
}
}
}
return ans;
}
int findMaximumXOR(vector<int>& nums) {
int n = nums.size();
TrieNode* root = new TrieNode();
int ans = 0;
for (int i = 0; i < n; i++) {
insert(root, nums[i]); //it will make trie by inserting values
}
for (int i = 1; i < n; i++) {
ans = max(ans, findmax(root, nums[i])); //find the necessary complementory values and maximum store
}
return ans;
}
}; | 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;
let ans = 0;
for(let i = 31; i >= 0; i--) {
const isSet = ((num >> i) & 1);
const opp = 1 - isSet;
const hasOpp = p[opp];
if(hasOpp) {
ans = ans | (1<<i);
p = p[opp];
} else {
p = p[isSet];
}
}
return ans;
}
for(let num of nums) {
add(num);
}
let max = 0;
for(let num of nums) {
max = Math.max(max, xor(num))
}
return max;
}; | 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 digits, followed by a dot '.'.
One or more digits, followed by a dot '.', followed by one or more digits.
A dot '.', followed by one or more digits.
An integer can be split up into these components (in order):
(Optional) A sign character (either '+' or '-').
One or more digits.
For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].
Given a string s, return true if s is a valid number.
Example 1:
Input: s = "0"
Output: true
Example 2:
Input: s = "e"
Output: false
Example 3:
Input: s = "."
Output: false
Constraints:
1 <= s.length <= 20
s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.
| 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.parseDouble(s);
return true;
}
catch(Exception e){
return false;
}
}
} | /*
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:
bool isNumber(string s){
char stage = 0;
for(int i = 0; i<s.size(); ++i){
if( (s[i] == '+' || s[i] == '-') && (stage == 0 || stage == 5)){ stage++; }
else if((s[i] == 'e' || s[i] == 'E') && stage > 1 && stage < 5){ stage = 5; }
else if(s[i] == '.' && stage < 3) {
//both side of '.' do not have any digit then return false
if(stage <= 1 && ( i + 1 >= s.size() || !(s[i+1] >= '0' && s[i+1] <= '9')) ) return false;
stage = 3;
}else if(s[i] >= '0' && s[i] <= '9'){
if(!(stage == 2 || stage == 4 || stage == 7) ) stage++;
if(stage == 1 || stage == 6 ) stage++;
}else return false;
}
if(stage <= 1 || stage == 5 || stage == 6) return false;
return true;
}
}; | /**
* @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_LOWER_A = 'a'.charCodeAt(0);
const CHAR_CODE_LOWER_Z = 'z'.charCodeAt(0);
let sign = '';
let decimal = '';
let exponential = '';
let exponentialSign = '';
let num = '';
for(let i = 0; i < n; i += 1) {
const char = s[i];
const charCode = s.charCodeAt(i);
if(char === '+' || char === '-') {
if(i === n - 1) return false;
if(i === 0) {
sign = char;
continue;
}
if(exponentialSign.length > 0) return false;
if(!(s[i - 1] === 'e' || s[i - 1] === 'E')) return false;
exponentialSign = char;
continue;
}
if(char === '.') {
if(decimal.length > 0) return false;
if(exponential.length > 0) return false;
if(num.length === 0 && i === n - 1) return false;
decimal = char;
continue;
}
if(charCode === CHAR_CODE_UPPER_E || charCode === CHAR_CODE_LOWER_E) {
if(exponential.length > 0) return false;
if(i === n - 1) return false;
if(num.length === 0) return false;
exponential = char;
continue;
}
if(charCode >= CHAR_CODE_UPPER_A && charCode <= CHAR_CODE_UPPER_Z) {
return false;
}
if(charCode >= CHAR_CODE_LOWER_A && charCode <= CHAR_CODE_LOWER_Z) {
return false;
}
num += char;
}
return true;
}; | 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 = [0,1,2,3,4,5,6,7,8]
Output: [0,1,2,4,8,3,5,6,7]
Explantion: [0] is the only integer with 0 bits.
[1,2,4,8] all have 1 bit.
[3,5,6] have 2 bits.
[7] has 3 bits.
The sorted array by bits is [0,1,2,4,8,3,5,6,7]
Example 2:
Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]
Output: [1,2,4,8,16,32,64,128,256,512,1024]
Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.
Constraints:
1 <= arr.length <= 500
0 <= arr[i] <= 104
| 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])
ls = []
for k in z:
ls.append(k[0])
return ls | 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 b) {
int aBits=numOfBits(a);
int bBits=numOfBits(b);
if(aBits==bBits) {
return a-b;
}
return aBits-bBits;
}
});
for(int i=0;i<arr.length;i++) {
arr[i]=arrInt[i];
}
return arr;
}
public int numOfBits(int a) {
int bits=0;
while(a!=0) {
bits+=a&1;
a=a>>>1;
}
return bits;
}
} | 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;
}
pq.push({count, x});
}
n = n - 1;
while(!pq.empty()) {
arr[n--] = pq.top().second;
pq.pop();
}
return arr;
}
}; | 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 division by 2)
}
map[n] = counter;
}
return arr.sort((a, b) => map[a] - map[b] || a - b) //sort by number of 1 bits; if equal, sort by value
}; | 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 <= s.length <= 105
s consists of lowercase English letters.
| 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_deleted:
return compare(s[1:], True) or compare(s[:-1], True)
else:
return False
return compare(s, has_deleted) | 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(!first){
first = true;
String removeLeft = s.substring(0,left).concat(s.substring(left+1));
String removeright = s.substring(0,right).concat(s.substring(right+1));
left++;
right--;
return validPalindrome(removeLeft) || validPalindrome(removeright);
} else {
return false;
}
}
return true;
}
} | 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 == s.size() / 2)) {
// abca. If we have pattern like this than we can delete one of the symbols
return true;
}
bool first_valid = true;
for (int i = diff; i < (s.size() + 1) / 2; ++i) {
if (s[i] != s[s.size() - 2 - i]) {
first_valid = false;
break;
}
}
bool second_valid = true;
for (int i = diff; i < (s.size() + 1) / 2; ++i) {
if (s[i + 1] != s[s.size() - 1 - i]) {
second_valid = false;
break;
}
}
return first_valid || second_valid;
}
}; | /*
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 pointer. Hence, we check if s[low+1...right] is a palindrome
or s[low...right-1] is a palindrome. If one of them is a palindrome, we know that we can form a palindrome with one deletion and return true. Else, we require more than one deletion, and hence we return false.
*/
var validPalindrome = function(s) {
let low = 0, high = s.length-1;
while (low < high) {
if (s[low] !== s[high]) {
return isPalindrome(s, low+1, high) || isPalindrome(s, low, high-1);
}
low++, high--;
}
return true;
// T.C: O(N)
// S.C: O(1)
};
function isPalindrome(str, low, high) {
while (low < high) {
if (str[low] !== str[high]) return false;
low++, high--;
}
return true;
} | 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 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
The number of nodes in each linked list is in the range [1, 100].
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.
| 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 None else 0
sum = digit1 + digit2 + carry
digit = sum % 10
carry = sum // 10
newNode = ListNode(digit)
tail.next = newNode
tail = tail.next
l1 = l1.next if l1 is not None else None
l2 = l2.next if l2 is not None else None
result = dummyHead.next
dummyHead.next = None
return result | 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){
int sum = 0;
if(l1 != null){
sum += l1.val;
l1 = l1.next;
}
if(l2 != null){
sum += l2.val;
l2 = l2.next;
}
sum += carry;
carry = sum / 10;
ListNode node = new ListNode(sum % 10);
temp.next = node;
temp = temp.next;
}
return dummy.next;
}
} | 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 = res/10;
head1->val = res%10;
if(!head3){
head3 = head1;
temp = head3;
}
else{
temp->next = head1;
temp = temp->next;
}
head1 = head1->next;
head2 = head2->next;
}
while(head1){
res = head1->val + carry;
carry = res/10;
head1->val = res%10;
temp->next = head1;
temp = temp->next;
head1 = head1->next;
}
while(head2){
res = head2->val + carry;
carry = res/10;
head2->val = res%10;
temp->next = head2;
temp = temp->next;
head2 = head2->next;
}
if(carry){
ListNode* result = new ListNode();
result->val = carry;
result->next = NULL;
temp->next = result;
temp = temp->next;
}
return head3;
}
}; | /**
* 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;
var carry = 0;
while(l1!==null||l2!==null||sum>0){
if(l1!==null){
sum = sum + l1.val;
l1 = l1.next;
}
if(l2!==null){
sum = sum + l2.val;
l2 = l2.next;
}
if(sum>=10){
carry = 1;
sum = sum - 10;
}
head.next = new ListNode(sum);
head = head.next;
sum = carry;
carry = 0;
}
return List.next;
}; | 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 digit 2 occurs 2 times.
It is also the smallest numerically balanced number strictly greater than 1.
Example 2:
Input: n = 1000
Output: 1333
Explanation:
1333 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times.
It is also the smallest numerically balanced number strictly greater than 1000.
Note that 1022 cannot be the answer because 0 appeared more than 0 times.
Example 3:
Input: n = 3000
Output: 3133
Explanation:
3133 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times.
It is also the smallest numerically balanced number strictly greater than 3000.
Constraints:
0 <= n <= 106
| 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],
7: [1224444, 2255555, 3334444, 1666666, 7777777]
}
if n >= int(str(n_digits) * n_digits):
n_digits += 1
return min(next_max[n_digits])
ans = float('inf')
for num in sorted(next_max[n_digits]):
cands = set(permutations(str(num)))
cands = sorted(map(lambda x: int("".join(x)), cands))
loc = bisect.bisect(cands, n)
if loc < len(cands):
ans = min(ans, cands[loc])
return ans | 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
num = num / 10; //this is quotient
freq[rem] = freq[rem] + 1; //increase its frequency
if(freq[rem] > rem) break;
}
boolean ans = true;
for(int i = 0;i<10;i++){ //check frequency of each digit
if(freq[i] != i && freq[i] != 0){
ans = false;
break;
}
}
if(ans == true){
return n;
}
}
}
} | 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 nextBeautifulNumber(int n) {
while(true)
{
++n;
if(valid(n))
return n;
}
return 1;
}
}; | /**
* @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 balanced number
}
}
function isNumericallyBalanced(n){
let map={},d,nStr=n.toString();
while(n>0){//Create a map of digits with frequency
d = n%10;
if(d>nStr.length){//If we have found a digit greater than the lenght of the number like 227333, here when we see 7, we can return false
return false;
}
if(map[d]===undefined){
map[d]=1;
}else{
map[d]++;
if(map[d]>d){//If a digit has frequency more than its value, for example 22333344, here when we see fourth 3 than we can return false
return false;
}
}
n = Math.floor(n/10);
}
for(let key in map){//Check if frequency is equal to the digit
if(map[key]!==parseInt(key)){
return false;
}
}
return true;
}
}; | 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 of "abcde" while "aec" is not).
Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false
Constraints:
0 <= s.length <= 100
0 <= t.length <= 104
s and t consist only of lowercase English letters.
Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code? | 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]:
subsequence+=1
return subsequence == len(s) | 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
return false;
}
return true;
}
} | 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 s
for (int i = 0; i < m and j < n; i++)
if (s[j] == t[i])
j++;
// If all characters of s were found in t
return (j == n);
}
}; | /**
* @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: s1 = "ab", s2 = "eidboaoo"
Output: false
Constraints:
1 <= s1.length, s2.length <= 104
s1 and s2 consist of lowercase English letters.
| 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:
s1_map[i] += 1
l = 0
r = 0
while r < len(s2):
print(s2_map , l ,r)
if r == 0:
while r < len(s1):
s2_map[s2[r]] += 1
r += 1
if s2_map == s1_map:
return True
else:
s2_map[s2[l]] -= 1
s2_map[s2[r]] += 1
if s2_map == s1_map:
return True
else:
l += 1
r += 1
return False | 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);
char s = s2.charAt(i);
s1Count[c - 'a'] += 1;
s2Count[s - 'a'] += 1;
}
int matches = 0;
for(int i = 0; i < 26;i++) {
if(s1Count[i] == s2Count[i]) {
matches+=1;
}
}
int left = 0;
for(int right = s1.length(); right < s2.length();right++) {
if(matches == 26) {
return true;
}
int index = s2.charAt(right) - 'a';
s2Count[index] += 1;
if(s1Count[index] == s2Count[index]) {
matches += 1;
}
else if(s1Count[index] + 1 == s2Count[index]) {
matches -= 1;
}
index = s2.charAt(left) - 'a';
s2Count[index] -= 1;
if(s1Count[index] == s2Count[index]) {
matches += 1;
}
else if(s1Count[index] - 1 == s2Count[index]) {
matches -= 1;
}
left += 1;
}
if(matches == 26) {
return true;
}
return false;
}
} | 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 false;
let l = 0, r = 0;
for(; r < s1Len ; r++) {
occS1[getCharIdx(s1[r])]++;
occS2[getCharIdx(s2[r])]++;
}
if(isEqual(occS1, occS2)) {
return true;
}
for(; r < s2Len; r++) {
occS2[getCharIdx(s2[r])]++;
occS2[getCharIdx(s2[l++])]--;
if(isEqual(occS1, occS2)) return true;
}
return false;
}; | 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 unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.
Return the minimum number of moves that you need to determine with certainty what the value of f is.
Example 1:
Input: n = 2
Output: 2
Explanation: We can drop the first egg from floor 1 and the second egg from floor 2.
If the first egg breaks, we know that f = 0.
If the second egg breaks but the first egg didn't, we know that f = 1.
Otherwise, if both eggs survive, we know that f = 2.
Example 2:
Input: n = 100
Output: 14
Explanation: One optimal strategy is:
- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.
- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.
- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.
Regardless of the outcome, it takes at most 14 drops to determine f.
Constraints:
1 <= n <= 1000
| 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 dp[n][egg];
int min = n; // when you drop at each floor starting from 1
for(int i = 1; i < n; i++) {
int eggBreak = 1 + eggDrop(i-1, egg-1, dp); // drops needed if egg breaks at this floor
int noEggBreak = 1 + eggDrop(n-i, egg, dp); // drops needed if egg does not break at this floor
int moves = Math.max(eggBreak, noEggBreak); // since we want certain moves for n floor take max
min = Math.min(min, moves);
}
dp[n][egg] = min;
return min;
}
} | 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){
int mid = left + (right-left)/2;
int left_result = solve(e-1,mid-1);
int right_result = solve(e,f-mid);
mn = min(mn,1+max(left_result, right_result));
if(left_result<right_result)
left = mid+1;
else
right = mid-1;
}
return dp[e][f] = mn;
}
int twoEggDrop(int n) {
memset(dp, -1, sizeof(dp));
return solve(2,n);
}
}; | /** 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
// Diff from prev: 13 12 11 10 9 8 7 6 5 4 3 2 1
// So we have hypothesis algorithm
// That is, `n` minus `d` until `result(n)` is smaller than `d`, where `d` start at 1 and increment by 1 for each iteration. If `result(n)` is 0, subtract 1, else return the result
let d = 1;
while (n > d) {
n -= d;
d++;
}
if (n == 0) {
d--;
}
return d;
}; | 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 possible.
Return the maximum number of ice cream bars the boy can buy with coins coins.
Note: The boy can buy the ice cream bars in any order.
Example 1:
Input: costs = [1,3,2,4,1], coins = 7
Output: 4
Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
Example 2:
Input: costs = [10,6,8,7,7,8], coins = 5
Output: 0
Explanation: The boy cannot afford any of the ice cream bars.
Example 3:
Input: costs = [1,6,3,1,2,5], coins = 20
Output: 6
Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
Constraints:
costs.length == n
1 <= n <= 105
1 <= costs[i] <= 105
1 <= coins <= 108
| 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
if(coins - cost >= 0) {
coins -= cost;
count++;
}
}
return count;
}
} | 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 the length of costs.
}
}
return count;
}; | 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 of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation: We return the node with value 2, colored in yellow in the diagram.
The nodes coloured in blue are the deepest leaf-nodes of the tree.
Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.
Example 2:
Input: root = [1]
Output: [1]
Explanation: The root is the deepest node in the tree, and it's the lca of itself.
Example 3:
Input: root = [0,1,3,null,2]
Output: [2]
Explanation: The deepest leaf node in the tree is 2, the lca of one node is itself.
Constraints:
The number of nodes in the tree will be in the range [1, 1000].
0 <= Node.val <= 1000
The values of the nodes in the tree are unique.
Note: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
| 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])
elif lvl == self.max_lvl[0]:
self.max_lvl = (lvl,self.max_lvl[1]+[root])
self.pathes[root] = parent
rec(root.left,root,lvl+1)
rec(root.right,root,lvl+1)
rec(root,None,0)
print(self.max_lvl)
# for key in self.pathes:
# if key!=None and self.pathes[key]!=None:
# print(key.val,"-",self.pathes[key].val)
if len(self.max_lvl[1]) < 2:
return self.max_lvl[1][0]
parent = self.max_lvl[1]
while len(parent) > 1:
temp = set()
for p in parent:
temp.add(self.pathes.get(p,None))
parent = temp
return parent.pop() | 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 = q.size();
count++;
if (count == depth) {
break;
}
for (int i = 0; i < size; i++) {
TreeNode cur = q.poll();
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
}
Set<Integer> set = new HashSet<>();
while (!q.isEmpty()) {
set.add(q.poll().val);
}
return find(root, set);
}
public int findDepth(TreeNode root) {
if (root == null) return 0;
int left = findDepth(root.left);
int right = findDepth(root.right);
return 1 + Math.max(left, right);
}
public TreeNode find(TreeNode root, Set<Integer> set) {
if (root == null) return root;
if (set.contains(root.val)) return root;
TreeNode left = find(root.left, set);
TreeNode right = find(root.right, set);
if (left != null && right != null) return root;
else if (left != null) return left;
else if (right != null) return right;
else return null;
}
} | 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);
}
else if(h>mx){
vec.clear();
vec.push_back(root);
mx = h;
}
}
bool uf = 0;
void check(TreeNode * root, TreeNode * it){
if(!root or uf) return ;
st.push(root);
if(root->val == it->val){
uf = 1;
return ;
}
check(root->left, it);
check(root->right, it);
if(!uf)
st.pop();
}
TreeNode* lcaDeepestLeaves(TreeNode* root) {
vec.clear();
ch(root, 0);
vector<vector<TreeNode *>>ans;
ans.clear();
int mnx = INT_MAX;
for(auto it:vec){
uf = 0;
check(root, it);
vector<TreeNode *>temp;
while(!st.empty()){
temp.push_back(st.top());
st.pop();
}
reverse(temp.begin(), temp.end());
ans.push_back(temp);
int p = temp.size();
mnx = min(mnx, p);
}
TreeNode * rt = new TreeNode(0);
if(ans.size() == 1){
return ans[0][ans[0].size()-1];
}
bool lb = 0;
for(int j=0; j<mnx; j++){
for(int i=0; i<ans.size()-1; i++){
if(ans[i][j]==ans[i+1][j]){
continue;
}
else{
rt = ans[i][j-1];
lb = 1;
break;
}
}
if(lb) break;
}
return rt;
}
}; | 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 + 1);
const rd = compute(r.right, d + 1);
if(ld == rd && ld == md) {
ans = r;
}
return Math.max(ld, rd);
}
compute();
return ans;
}; | 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 an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.
The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.
Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2
Output: 0.78333
Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
Example 2:
Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4
Output: 0.53485
Constraints:
1 <= classes.length <= 105
classes[i].length == 2
1 <= passi <= totali <= 105
1 <= extraStudents <= 105
| 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]
totalCount = classes[i][1]
# calculate the impact for class i
currentRatio = passCount/totalCount
expectedRatioAfterUpdate = (passCount+1)/(totalCount+1)
impact = expectedRatioAfterUpdate - currentRatio
impacts[i] = (-impact, passCount, totalCount) # note the - sign for impact
heapq.heapify(impacts)
while(extraStudents > 0):
# pick the next class with greatest impact
_, passCount, totalCount = heapq.heappop(impacts)
# assign a student to the class
passCount+=1
totalCount+=1
# calculate the updated impact for current class
currentRatio = passCount/totalCount
expectedRatioAfterUpdate = (passCount+1)/(totalCount+1)
impact = expectedRatioAfterUpdate - currentRatio
# insert updated impact back into the heap
heapq.heappush(impacts, (-impact, passCount, totalCount))
extraStudents -= 1
result = 0
# for all the updated classes calculate the total passRatio
for _, passCount, totalCount in impacts:
result += passCount/totalCount
# return the average pass ratio
return result/n | 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 bdiff = (b[0]+1)/(b[1]+1) - (b[0]/b[1]);
if(adiff==bdiff) return 0;
return adiff>bdiff? -1:1;
}
});
for(int[] c:classes) pq.add(new double[]{c[0],c[1]});
for(int i =0;i<extraStudents;i++){
double[] curr = pq.poll();
pq.add(new double[]{curr[0]+1,curr[1]+1});
}
double sum = 0;
while(!pq.isEmpty()){
double[] curr = pq.poll();
sum+=curr[0]/curr[1];
}
return sum/classes.length;
}
} | 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(vector<vector<int>>& classes, int extraStudents) {
double acc = 0;
priority_queue<pair<int,int>, vector<pair<int,int>>, cmp> que;
for(vector<int> i: classes)
que.push(make_pair(i[0],i[1]));
while(extraStudents--){
pair<int,int> cur = que.top(); que.pop();
cur.first++, cur.second++;
que.push(cur);
}
while(!que.empty()){
pair<int,int> cur = que.top(); que.pop();
acc += cur.first / (double) cur.second;
}
return acc / (double) classes.size();
}
}; | /**
* @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) {
return null;
}
if (this.heap.length === 1) {
return this.heap.pop();
}
const top = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown(0);
return top;
}
heapifyUp(index) {
while (index > 0) {
const parent = Math.floor((index - 1) / 2);
if (this.heap[parent][0] < this.heap[index][0]) {
[this.heap[parent], this.heap[index]] = [this.heap[index], this.heap[parent]];
index = parent;
} else {
break;
}
}
}
heapifyDown(index) {
const n = this.heap.length;
while (true) {
let largest = index;
const left = 2 * index + 1;
const right = 2 * index + 2;
if (left < n && this.heap[left][0] > this.heap[largest][0]) {
largest = left;
}
if (right < n && this.heap[right][0] > this.heap[largest][0]) {
largest = right;
}
if (largest !== index) {
[this.heap[index], this.heap[largest]] = [this.heap[largest], this.heap[index]];
index = largest;
} else {
break;
}
}
}
size() {
return this.heap.length;
}
}
var maxAverageRatio = function(classes, extraStudents) {
const n = classes.length;
// Helper function to calculate pass ratio increase
const passRatioIncrease = (pass, total) => (pass + 1) / (total + 1) - pass / total;
// Initialize max heap to keep track of classes with maximum improvement
const maxHeap = new MaxHeap();
for (let j = 0; j < n; j++) {
const [pass, total] = classes[j];
if (pass !== total) {
const increase = passRatioIncrease(pass, total);
maxHeap.push([increase, j]);
}
}
let totalPassRatio = 0;
for (let j = 0; j < n; j++) {
totalPassRatio += classes[j][0] / classes[j][1];
}
for (let i = 0; i < extraStudents; i++) {
if (maxHeap.size() === 0) {
break; // No more classes to consider
}
const [increase, maxIndex] = maxHeap.pop();
const [pass, total] = classes[maxIndex];
const newPass = pass + 1;
const newTotal = total + 1;
const newIncrease = passRatioIncrease(newPass, newTotal);
const newAvg = (totalPassRatio - (pass / total)) + (newPass / newTotal);
if (newAvg <= totalPassRatio) {
break; // No further improvement possible
}
totalPassRatio = newAvg;
classes[maxIndex][0]++;
classes[maxIndex][1]++;
maxHeap.push([newIncrease, maxIndex]);
}
return totalPassRatio / n;
}; | 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 only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
Example 1:
Input: n = 3
Output: 5
Explanation: The five different ways are show above.
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 1000
| 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 array
for (var i = len - 1; i <= n;i++) {
ways[i % len] = (
ways[(len + i - 1) % len] * 2
+
ways[(len + i - 3) % len]
) % mod;
}
return ways[(i - 1) % len];
}; | 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
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
Example 2:
Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.
Constraints:
2 <= nums.length <= 50
0 <= nums[i] <= 100
The largest element in nums is unique.
| 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;
for(int i = 0; i < nums.length; i++){
if(nums[i] > max){
secondMax = max;
max = nums[i];
index = i;
} else if(nums[i] != max && nums[i] > secondMax){
secondMax = nums[i];
}
}
if(secondMax * 2 <= max){
return index;
}
return -1;
}
} | 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;
max2 = max1;
max1 = nums[i];
}else if(nums[i] > max2){
max2 = nums[i];
}
}
return max1 >= 2*max2 ? result : -1;
}
}; | /**
* @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) {
second = nums[i];
}
}
return first >= second * 2 ? ans : -1;
}; | 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 = "abccbaacz"
Output: "c"
Explanation:
The letter 'a' appears on the indexes 0, 5 and 6.
The letter 'b' appears on the indexes 1 and 4.
The letter 'c' appears on the indexes 2, 3 and 7.
The letter 'z' appears on the index 8.
The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.
Example 2:
Input: s = "abcdd"
Output: "d"
Explanation:
The only letter that appears twice is 'd' so we return 'd'.
Constraints:
2 <= s.length <= 100
s consists of lowercase English letters.
s has at least one repeated letter.
| 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 = it;
break;
}
mp[it]++; //increase the count of char
}
return ans;
}
}; | 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 the array is good otherwise return False.
Example 1:
Input: nums = [12,5,7,23]
Output: true
Explanation: Pick numbers 5 and 7.
5*3 + 7*(-2) = 1
Example 2:
Input: nums = [29,6,10]
Output: true
Explanation: Pick numbers 29, 6 and 10.
29*1 + 6*(-3) + 10*(-1) = 1
Example 3:
Input: nums = [3,6]
Output: false
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
| 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){
return a;
}
else{
return GCD(b, a%b);
}
}
} | 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
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Constraints:
1 <= n <= 45
| 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
return memo[n]
else: # Store the recurssion function in the look-up table and reuturn the stored look-up table function
memo[n] = climb(n-1) + climb(n-2)
return memo[n]
return climb(n) | 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];
}
memo[n] = calculateWays(n - 1, memo) + calculateWays(n - 2, memo);
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 step)
*/
var climbStairs = function(n) {
let dp = new Array(n + 1);
dp[1] = 1, dp[2] = 2;
for (let i = 3; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
// T.C: O(N)
// S.C: O(N)
}; | 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 obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.
Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.
In case there is no path, return [0, 0].
Example 1:
Input: board = ["E23","2X2","12S"]
Output: [7,1]
Example 2:
Input: board = ["E12","1X1","21S"]
Output: [4,2]
Example 3:
Input: board = ["E11","XXX","11S"]
Output: [0,0]
Constraints:
2 <= board.length == board[i].length <= 100
| 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 DP
@cache
def visit(i, j):
if i == h-1 and j == w-1:
## Base case:
# score for start coordinate = 0
# paht count for start coordinate = 1
return 0, 1
elif i >= w or j >= h or board[i][j] == 'X':
## Base case:
# Out-of-boundary, or meet obstacle
return 0, 0
## General case:
# update from three possible preivous moves from right, down, and diagonal
right_score, right_path_count = visit(i, j+1)
down_score, down_path_count = visit(i+1, j)
diag_score, diag_path_count = visit(i+1, j+1)
max_prevScore = max(right_score, down_score, diag_score)
cur_path_count = 0
cur_score = int(board[i][j]) if board[i][j] != "E" else 0
if right_score == max_prevScore : cur_path_count += right_path_count
if down_score == max_prevScore : cur_path_count += down_path_count
if diag_score == max_prevScore : cur_path_count += diag_path_count
return max_prevScore + cur_score, cur_path_count
# ----------------------------------------------------------------------------
## Remark: Remember to take modulo by constant, this is defined by description
CONST = 10**9 + 7
maxScore, validPathCount = visit(0, 0)
return [maxScore % CONST, validPathCount % CONST] if validPathCount else [0, 0] | 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}, {-1, -1}}; // all 3 ways where we can travel.
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
if (board.get(i).charAt(j)=='X'){
continue;
}
int cur = Character.isDigit(board.get(i).charAt(j))?board.get(i).charAt(j)-'0':0;
for (int[] d : dirs){
int x = d[0]+i;
int y = d[1]+j;
if (x < 0 || y < 0 || ways[x][y] == 0){
continue;
}
if (cur+dp[x][y]>dp[i][j]){
dp[i][j]=cur+dp[x][y];
ways[i][j]=0;
}
if (cur+dp[x][y]==dp[i][j]){
ways[i][j]+=ways[x][y];
ways[i][j]%=M;
}
}
}
}
return new int[]{dp[m-1][n-1], ways[m-1][n-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<0 || j<0 || i>=n || j>=m || board[i][j]=='X')return {INT_MIN,0};
//check if it is stored or not
if(h.find({i,j})!=h.end())return h[{i,j}];
int no=0,cnt=0;
if(board[i][j]!='S')no=board[i][j]-'0';
//top ,left ,top left
auto a=solve(board,i-1,j,n,m);
auto b=solve(board,i,j-1,n,m);
auto c=solve(board,i-1,j-1,n,m);
//maxi ans
int curr=(max(a.first,max(b.first,c.first)))%mod;
//if maxi ans == a , b , c then increament count of a ,b,c
if(curr==a.first)cnt+=a.second;
if(curr==b.first)cnt+=b.second;
if(curr==c.first)cnt+=c.second;
return h[{i,j}]={(curr+no)%mod,cnt%mod};
}
vector<int> pathsWithMaxScore(vector<string>& board) {
auto ans=solve(board,board.size()-1,board[0].size()-1,board.size(),board[0].size());
if(ans.first<0)return {0,0};
return {ans.first%mod,ans.second%mod};
}
}; | 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--) {
if (board[i][j] === 'X' || board[i][j] === 'S') continue;
let paths = [dp[i][j + 1], dp[i + 1][j + 1], dp[i + 1][j]];
for (let [maxScore, numPaths] of paths) {
if (dp[i][j][0] < maxScore) {
dp[i][j] = [maxScore, numPaths];
} else if (dp[i][j][0] === maxScore) {
dp[i][j][1] = (dp[i][j][1] + numPaths) % mod;
}
}
let score = board[i][j] === 'E' ? 0 : Number(board[i][j]);
dp[i][j][0] += score;
}
}
return dp[0][0][1] === 0 ? [0, 0] : dp[0][0];
}; | 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 end, find the path with the maximum probability of success to go from start to end and return its success probability.
If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.
Example 1:
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
Output: 0.25000
Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.
Example 2:
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
Output: 0.30000
Example 3:
Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
Output: 0.00000
Explanation: There is no path between 0 and 2.
Constraints:
2 <= n <= 10^4
0 <= start, end < n
start != end
0 <= a, b < n
a != b
0 <= succProb.length == edges.length <= 2*10^4
0 <= succProb[i] <= 1
There is at most one edge between every two nodes.
| 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+=1
heapq.heappush(heap,[-1.0,start])
dist[start]=1
while(heap):
prob,u=heapq.heappop(heap)
for v,w in adj[u]:
if(dist[v]>-abs(w*prob)):
dist[v]=-abs(w*prob)
heapq.heappush(heap,[dist[v],v])
if(sys.maxsize==dist[end]):
return 0.00000
else:
return -dist[end] | 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++){
adj.add(new ArrayList<Pair>());
}
for(int i=0;i<edges.length;i++){
adj.get(edges[i][0]).add(new Pair(edges[i][1],succProb[i]));
adj.get(edges[i][1]).add(new Pair(edges[i][0],succProb[i]));
}
//node,to node,probability
double probs[]=new double[n];
Arrays.fill(probs,0.0);
probs[start]=1.0;
PriorityQueue<Pair> pq=new PriorityQueue<>((p1,p2)->Double.compare(p2.prob,p1.prob));
pq.offer(new Pair(start,1.0));
while(!pq.isEmpty()){
Pair curr=pq.poll();
for(Pair x:adj.get(curr.to)){
if(((curr.prob)*(x.prob))>probs[x.to]){
probs[x.to]=((curr.prob)*(x.prob));
pq.offer(new Pair(x.to,probs[x.to]));
}
else{
continue;
}
}
}
return probs[end];
}
} | 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[edges[i][1]].push_back({edges[i][0], succProb[i]});
}
priority_queue<pair<double, int>> pq;
pq.push({1.0, start});
vector<bool> visited(n, false);
vector<double> values(n, 0.0);
values[start] = 1.0;
while(!pq.empty()){
double currValue = pq.top().first, currNode = pq.top().second;
pq.pop();
visited[currNode] = true;
for(int i = 0; i < graph[currNode].size(); ++i){
double weight = graph[currNode][i].second;
int nextNode = graph[currNode][i].first;
if(visited[nextNode] == false){
double nextProb = currValue * weight;
if(nextProb > values[nextNode])
values[nextNode] = nextProb;
pq.push({nextProb, nextNode});
}
}
}
return values[end] == 0.0 ? 0.0 : values[end];
}
}; | 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, bSet);
});
const dist = new Array(n).fill(0);
const vis = new Array(n).fill(false);
dist[start] = 1;
const getMaxProbNode = () => {
let maxVal = 0, maxIndex = -1;
for(let i = 0; i < n; i++) {
if(maxVal < dist[i] && !vis[i]) {
maxVal = dist[i], maxIndex = i;
}
}
return maxIndex;
}
for(let i = 0; i < n - 1; i++) {
const maxProbNode = getMaxProbNode();
vis[maxProbNode] = true;
const adjacentNodes = graph.get(maxProbNode) || [];
const len = adjacentNodes.length;
for(let j = 0; j < len; j++) {
const [node, prob] = adjacentNodes[j];
if(!vis[node] && dist[node] < dist[maxProbNode] * prob) {
dist[node] = dist[maxProbNode] * prob;
}
}
}
return dist[end];
}; | 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) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.
Example 2:
Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
Constraints:
1 <= n <= 104
nums.length == 2 * n
-104 <= nums[i] <= 104
| 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:
1 <= numRows <= 30
| 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):
tmp.append(ans[x][k] + ans[x][k + 1])
tmp.append(1)
ans.append(tmp)
return ans | 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> temp = list.get(i);
List<Integer> temp2 = new ArrayList();
temp2.add(1);
for(int j = 0; j < temp.size() - 1; j++) {
temp2.add(temp.get(j) + temp.get(j+1));
}
temp2.add(1);
list.add(temp2);
}
return list;
}
} | 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{
ans[i].push_back(ans[i-1][j-1] + ans[i-1][j]);
}
}
}
return ans;
}
}; | 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] = val
}
ans[i] = row
}
return ans
}; | 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 sum is defined as the sum of a node and its twin.
Given the head of a linked list with even length, return the maximum twin sum of the linked list.
Example 1:
Input: head = [5,4,2,1]
Output: 6
Explanation:
Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
There are no other nodes with twins in the linked list.
Thus, the maximum twin sum of the linked list is 6.
Example 2:
Input: head = [4,2,2,3]
Output: 7
Explanation:
The nodes with twins present in this linked list are:
- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
Thus, the maximum twin sum of the linked list is max(7, 4) = 7.
Example 3:
Input: head = [1,100000]
Output: 100001
Explanation:
There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.
Constraints:
The number of nodes in the list is an even integer in the range [2, 105].
1 <= Node.val <= 105
| 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])
return res | /**
* 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) {
if (head == null) {
return 0;
}
if (head.next == null) {
return head.val;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
slow = reverse(slow);
fast = head;
int sum = Integer.MIN_VALUE;
while (slow != null) {
sum = Math.max(slow.val + fast.val, sum);
slow = slow.next;
fast = fast.next;
}
return sum;
}
public ListNode reverse(ListNode node) {
if (node == null) {
return null;
}
ListNode current = node;
ListNode previous = null;
while (current != null) {
ListNode next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
} | 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(ListNode* head){
ListNode* slowptr=head,*fastptr=head->next;
while(fastptr&&fastptr->next){
slowptr=slowptr->next;
fastptr=fastptr->next->next;
}
return slowptr;
}
int pairSum(ListNode* head) {
int ans=0;
ListNode* midNode=findMiddleNode(head);
ListNode* head2=reverse(midNode->next);
midNode->next=NULL;
ListNode* p1=head,*p2=head2;
while(p1&&p2){
ans=max(ans,p1->val+p2->val);
p1=p1->next;
p2=p2->next;
}
midNode->next=reverse(head2);
return ans;
}
}; | 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 means a street connecting the right cell and the lower cell.
5 which means a street connecting the left cell and the upper cell.
6 which means a street connecting the right cell and the upper cell.
You will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.
Notice that you are not allowed to change any street.
Return true if there is a valid path in the grid or false otherwise.
Example 1:
Input: grid = [[2,4,3],[6,5,2]]
Output: true
Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).
Example 2:
Input: grid = [[1,2,1],[1,2,1]]
Output: false
Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)
Example 3:
Input: grid = [[1,1,2]]
Output: false
Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
1 <= grid[i][j] <= 6
| 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)]
}
q=collections.deque([(0,0)])
visit=set()
while q:
i,j=q.popleft()
visit.add((i,j))
if i==r-1 and j==c-1:
return True
for x,y in dic[grid[i][j]]:
nx=i+x
ny=j+y
if nx>=0 and nx<r and ny>=0 and ny<c and (nx,ny) not in visit:
if (-x,-y) in dic[grid[nx][ny]]:
q.append((nx,ny))
return False | 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 true;
if(i<0 || i>=m || j<0 || j>=n || visited[i][j]==1) return false;
visited[i][j]=1;
if(grid[i][j]==1){
if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) ||
(j<n-1 && (grid[i][j+1]==1 || grid[i][j+1]==3 || grid[i][j+1]==5 ) && dfs(grid, i, j+1, m, n, visited) )) return true;
}else if(grid[i][j]==2){
if( (i<m-1 && (grid[i+1][j]==2 || grid[i+1][j]==5 || grid[i+1][j]==6) && dfs(grid, i+1, j, m, n, visited)) ||
(i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;
}else if(grid[i][j]==3){
if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) ||
(i<m-1 && (grid[i+1][j]==2 || grid[i+1][j]==5 || grid[i+1][j]==6) && dfs(grid, i+1, j, m, n, visited))) return true;
}else if(grid[i][j]==4){
if( ((i<m-1 && (grid[i+1][j]==2 || grid[i+1][j]==5 || grid[i+1][j]==6)) && dfs(grid, i+1, j, m, n, visited)) ||
(j<n-1 && (grid[i][j+1]==1 || grid[i][j+1]==3 || grid[i][j+1]==5) && dfs(grid, i, j+1, m, n, visited))) return true;
}else if(grid[i][j]==5){
if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) ||
(i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;
}else{
if( (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited)) ||
(j<n-1 && (grid[i][j+1]==1 || grid[i][j+1]==3 || grid[i][j+1]==5) && dfs(grid, i, j+1, m, n, visited))) return true;
}
return false;
}
} | 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, means we need to follow "street-4" direction
// First index of street-4 direction = 2*(4-1) = 6
// Second index of street-4 direction = 2*(4-1)+1 = 7
// dir[6] = {0, 1}
// dir[7] = {1, 0}
vector<vector<int>>dir = { // Indices
{0,-1}, {0, 1}, // street 1 --> 0 1
{-1,0}, {1, 0}, // street 2 --> 2 3
{0,-1}, {1, 0}, // street 3 --> 4 5
{0, 1}, {1, 0}, // street 4 --> 6 7
{0,-1}, {-1,0}, // street 5 --> 8 9
{0, 1}, {-1,0} // street 6 --> 10 11
};
vector<vector<bool>>vis(m, vector<bool>(n, false));
queue<pair<int,int>>q;
q.push({0, 0});
vis[0][0] = true;
while (!q.empty())
{
auto cur = q.front(); q.pop();
int r = cur.first;
int c = cur.second;
int val = grid[r][c] - 1; // grid values 1 to 6
if(r==m-1 and c==n-1) return true;
// 2 directions from every cell
for(int k=0;k<2;k++) // k = 0, k = 1
{
int idx = 2*val+k; // get index
int nr = r + dir[idx][0];
int nc = c + dir[idx][1];
if (nr < 0 or nr >= m or nc < 0 or nc >= n or vis[nr][nc]==true) continue;
// for checking the back direction matches with current cell i.e forming path to next cell
for(int x=0;x<2;x++)
{
int i = 2*(grid[nr][nc]-1)+x; // get index
if(r == nr+dir[i][0] and c == nc+dir[i][1]){
vis[nr][nc] = true;
q.push({nr, nc});
}
}
}
}
return false;
}
}; | 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: [[0,1], [1,0]], adjs: [[1,3,5], [2,5,6]]},
5: {dirs: [[-1,0], [0,-1]],adjs: [[2,3,4], [1,4,6]]},
6: {dirs: [[-1,0], [0,1]], adjs: [[2,3,4], [1,3,5]]}
}
let path = Array.from({length: grid.length}, el => new Uint16Array(grid[0].length))
let y = 0, x = 0;
function getNextSegment(segment, y, x) {
let dir = 0;
let ny = y + SEGMENTS[segment].dirs[dir][0];
let nx = x + SEGMENTS[segment].dirs[dir][1];
if (ny < 0 || ny >= M || nx < 0 || nx >= N || path[ny][nx]) {
dir = 1;
ny = y + SEGMENTS[segment].dirs[dir][0];
nx = x + SEGMENTS[segment].dirs[dir][1];
}
return {dir, ny, nx}
}
function isValid(y, x) {
for (let i = 0; i < M*N; i++) {
if (y == M-1 && x == N-1) return true;
path[y][x] = i+1;
let cur = grid[y][x];
let next = getNextSegment(cur, y, x);
if (next.ny >= M || next.nx >= N) return false;
if (!SEGMENTS[cur].adjs[next.dir].includes(grid[next.ny][next.nx])) return false;
y = next.ny;
x = next.nx;
}
return false
}
if (grid[0][0] !== 4) return isValid(y, x);
path[0][0] = 1;
return isValid(y, x+1) || isValid(y+1, x);
}; | 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 is that the customer pays $5.
Note that you do not have any change in hand at first.
Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.
Example 1:
Input: bills = [5,5,5,10,20]
Output: true
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.
Example 2:
Input: bills = [5,5,10,10,20]
Output: false
Explanation:
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can not give the change of $15 back because we only have two $10 bills.
Since not every customer received the correct change, the answer is false.
Constraints:
1 <= bills.length <= 105
bills[i] is either 5, 10, or 20.
| 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:
return False
else:
if (change[10]>0) & (change[5]>0):
change[10]-=1
change[5]-=1
elif change[5]>=3:
change[5]-=3
else:
return False
return True | 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++;
}
else{
return false;
}
}
else if(p == 20){
if(count5 > 0 && count10 > 0){
count5--;
count10--;
}
else if(count5 == 0){
return false;
}
else if(count5<3){
return false;
}
else{
count5 -= 3;
}
}
}
return true;
}
} | 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;
if(change == 5)
{
if(m[5] > 0)
{
m[5]--;
}
else
{
return false;
}
}
//change = 10
else
{
if(m[10] > 0 and m[5] > 0)
{
m[10]--;
m[5]--;
}
else if(m[5] >= 3)
{
m[5] -= 3;
}
else
{
return false;
}
}
}
}
return true;
}
}; | * @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"] -= 1;
cashLocker["10"] += 1;
} else if (bills[i] === 20 && cashLocker["5"] >= 1 && cashLocker["10"] >= 1) {
cashLocker["5"] -= 1;
cashLocker["10"] -= 1;
} else if (bills[i] === 20 && cashLocker["5"] >= 3) {
cashLocker["5"] -= 3;
} else {
return false;
}
}
return true;
}; | 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.
Example 1:
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [2,3,0,1,4]
Output: 2
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 1000
| 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
return ans | 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);
}
L = R + 1;
R = localMaxRight;
result++;
}
return result;
}
} | 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 = 0;
for(i=1; i<=step; i++){
if(i+nums[index+i]>mx){
mx = i+nums[index+i];
jump_now = i;
}
}
step = 0;
index += jump_now;
}
return ans;
}
}; | **//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 previous maximum jump, we increase our jump...
if (i === prev) {
jump++;
prev = max;
}
}
return jump;
}; | 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 value of X after performing all the operations.
Example 1:
Input: operations = ["--X","X++","X++"]
Output: 1
Explanation: The operations are performed as follows:
Initially, X = 0.
--X: X is decremented by 1, X = 0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
Example 2:
Input: operations = ["++X","++X","X++"]
Output: 3
Explanation: The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.
Example 3:
Input: operations = ["X++","++X","--X","X--"]
Output: 0
Explanation: The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
--X: X is decremented by 1, X = 2 - 1 = 1.
X--: X is decremented by 1, X = 1 - 1 = 0.
Constraints:
1 <= operations.length <= 100
operations[i] will be either "++X", "X++", "--X", or "X--".
| 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,4] to [2,2,2,2].
The difference between the maximum and minimum is 2-2 = 0.
Example 2:
Input: nums = [1,5,0,10,14]
Output: 1
Explanation: Change the array [1,5,0,10,14] to [1,1,0,1,1].
The difference between the maximum and minimum is 1-0 = 1.
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
| 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;
}
Arrays.sort(nums);
int left = 0, right = 3;
int res = Integer.MAX_VALUE;
while(left <= 3){
int mini = nums[left];
int max = nums[nums.length - right - 1];
res = Math.min(res, max - mini);
left++;
right--;
}
return res;
}
} | 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[len-2] - nums[2] ), // 2 elements removed from start 1 from end
( nums[len-3] - nums[1] ), // 2 elements removed from end 1 from start
)
}; | 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 is a VPS.
We can similarly define the nesting depth depth(S) of any VPS S as follows:
depth("") = 0
depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's
depth("(" + A + ")") = 1 + depth(A), where A is a VPS.
For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.
Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length).
Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.
Return an answer array (of length seq.length) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple answers may exist, you may return any of them.
Example 1:
Input: seq = "(()())"
Output: [0,1,1,1,1,0]
Example 2:
Input: seq = "()(())()"
Output: [0,0,0,1,1,0,1,1]
Constraints:
1 <= seq.size <= 10000
| 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
return ans | 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 );
//initailly assuming all parenthesis belong to A so filling res with 0
int i = 0;
int addToA = 0, addToB = 0;
while(i < seq.length()){
if(seq[i] == '('){
if(addToA <= addToB){
//adding depth to A when it's depth is lesser or equal to b
indexA.push_back(i);
addToA ++;
}else{
indexB.push_back(i);
addToB++;
}
}else{
// removing depth from string whose depth is maximum as we have to keep the difference minimum
if(addToA >= addToB){
addToA--;
indexA.push_back(i);
}else{
indexB.push_back(i);
addToB--;
}
}
i++;
}
for(i = 0; i < indexB.size(); i++){
res[indexB[i]] = 1;
}
return res;
}
}; | /**
* @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 required sub-arrays, or return -1 if you cannot find such two sub-arrays.
Example 1:
Input: arr = [3,2,2,4,3], target = 3
Output: 2
Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.
Example 2:
Input: arr = [7,3,4,7], target = 7
Output: 2
Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
Example 3:
Input: arr = [4,3,2,6,2,3,4], target = 6
Output: -1
Explanation: We have only one sub-array of sum = 6.
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 1000
1 <= target <= 108
| 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 arr
windowSum += num
while windowSum > target:
# when the sum of current window is larger then target, shrink the left end of the window one by one until windowSum <= target
windowSum -= arr[l]
l += 1
# the case when we found a new target sub-array, i.e. current window
if windowSum == target:
# length of current window
curLen = r - l + 1
# min_till[l - 1]: the subarray with min len up till the previous position of left end of the current window:
# avoid overlap with cur window
# new_sum_of_two_subarray = length of current window + the previous min length of target subarray without overlapping
# , if < res, update res.
res = min(res, curLen + min_till[l - 1])
# Everytime we found a target window, update the min_till of current right end of the window,
# for future use when sum up to new length of sum_of_two_subarray and update the res.
min_till[r] = min(curLen, min_till[r - 1])
else:
# If windowSum < target: window with current arr[r] as right end does not have any target subarry,
# the min_till[r] doesn't get any new minimum update, i.e it equals to previous min_till at index r - 1.
min_till[r] = min_till[r - 1]
return res if res < float('inf') else -1
Time = O(n): when sliding the window, left and right pointers traverse the array once.
Space = O(n): we use one additional list min_till[] to record min length of target subarray till index i. | 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 i = 0; i < arr.length; i++) { //record preSum and index
sum += arr[i];
map.put(sum, i);
}
sum = 0;
int size = arr.length + 1, res = arr.length + 1;//note if we set size as MAX_VALUE the line 16 may overflow
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
if (map.containsKey(sum - target)) size = Math.min(size, i - map.get(sum - target)); //find the subarray from the previous index to current one
if (map.containsKey(sum + target)) res = Math.min(res, size + map.get(sum + target) - i); //from the current index to next one, this avoid overlap
}
return res == arr.length + 1 ? -1 : res;
}
} | 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){
sum-=arr[start++];
}
if(sum==target){
prefix[end]=min(prefix[end-1>=0 ? end-1 : 0],end-start+1);
}
else{
prefix[end]=prefix[end-1>=0 ? end-1 : 0];
}
}
sum=0;
start=n-1;
for(int end=n-1;end>=0;end--){
sum+=arr[end];
while(sum>target){
sum-=arr[start--];
}
if(sum==target){
suffix[end]=min(suffix[end+1<n ? end+1 : n-1],start-end+1);
}
else{
suffix[end]=suffix[end+1<n ? end+1 : n-1];
}
}
int res=INT_MAX;
for(int i=0;i<n-1;i++){
if(prefix[i]==INT_MAX || suffix[i+1]==INT_MAX){
continue;
}
res=min(res,prefix[i]+suffix[i+1]);
}
return res==INT_MAX ? -1 : res;
}
}; | 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){
curr-=arr[left++]
}
if(curr===target){
if(left>0&&best[left-1]!==Math.min()){
res=Math.min(res,best[left-1]+i-left+1)
}
bestSoFar=Math.min(bestSoFar,i-left+1)
}
best[i]=bestSoFar;
}
return res===Math.min()?-1:res
}; | 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 smallest string that s can be changed to after using the swaps.
Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
Constraints:
1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s only contains lower case English letters.
| 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.parentof[ele] = par
return par
return recur(ele)
def unify(self,ele1,ele2):
p1,p2 = self.find(ele1),self.find(ele2)
r1,r2 = self.rankof[p1],self.rankof[p2]
if p1==p2: return
if r1>r2:
self.parentof[p2] = p1
else:
self.parentof[p1]=p2
if r1==r2: self.rankof[p2]+=1
class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
dsu = DSU()
nodes = set()
smallest = [s[i] for i in range(len(s))]
for i,j in pairs:
dsu.unify(i,j)
nodes.add(i)
nodes.add(j)
groups = {}
for node in nodes:
par = dsu.find(node)
if par not in groups:
groups[par] = [node]
else:
groups[par].append(node)
for group in groups.values():
letters,k = sorted([s[i] for i in group]),0
for i in group:
smallest[i] = letters[k]
k+=1
return "".join(smallest) | 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;
}
//Union of All Pairs who belongs to same set
for(List<Integer> l : pairs){
int i = l.get(0);
int j = l.get(1);
int il = find(i);
int jl = find(j);
if(il != jl){
union(il,jl);
}
}
//To get the Character in sorted order
PriorityQueue<Character>[]pq = new PriorityQueue[s.length()];
for(int i=0;i<pq.length;i++){
pq[i] = new PriorityQueue<>();
}
for(int i=0;i<s.length();i++){
int il = find(i);
char ch = s.charAt(i);
pq[il].add(ch);
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<s.length();i++){
int il = find(i);
char ch = pq[il].remove();
sb.append(ch);
}
return sb.toString();
}
int find(int x){
if(parent[x] == x){
return x;
}else{
parent[x] = find(parent[x]);
return parent[x];
}
}
void union(int x,int y){
if(rank[x] < rank[y]){
parent[x] = y;
}else if(rank[y] < rank[x]){
parent[y] = x;
}else{
parent[x] = y;
rank[y]++;
}
}
} | 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());
string ans = s;
for(int i=0; i<s.length(); i++) parent[i] = i;
for(auto pair: pairs)
{
int p1 = findParent(pair[0]), p2 = findParent(pair[1]);
if(p1 != p2) parent[p2] = p1;
}
for(auto pair: pairs)
{
int p = findParent(pair[0]);
mp[p].insert(pair[0]);
mp[p].insert(pair[1]);
}
for(auto it: mp)
{
vector<char> part;
set<int> idx = it.second;
for(auto index: idx) part.push_back(s[index]);
sort(part.begin(), part.end());
auto index = idx.begin();
for(auto x: part) ans[*index] = x, ++index;
}
return ans;
}
}; | 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.forEach((charIndex, i) => result[charIndex] = chars[i])
}
return result.join("")
};
class UnionFind {
constructor(len) {
this.roots = Array.from({length: len}).map((_, i) => i);
this.rank = Array.from({length: len}).fill(1);
}
find(x) {
if (x == this.roots[x]) {
return x;
}
return this.roots[x] = this.find(this.roots[x])
}
union(x, y) {
let rootX = this.find(x);
let rootY = this.find(y);
if (this.rank[rootX] > this.rank[rootY]) {
this.roots[rootY] = rootX;
} else if (this.rank[rootX] < this.rank[rootY]) {
this.roots[rootX] = rootY;
} else { // ranks equal
this.roots[rootY] = rootX;
this.rank[rootX]++
}
}
disjointSets() {
const ds = {};
for(let i = 0; i < this.roots.length; i++) {
let currentRoot = this.find(i);
if (currentRoot in ds) {
ds[currentRoot].push(i);
} else {
ds[currentRoot] = [i];
}
}
return ds;
}
} | 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 there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1.
Example 1:
Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
Example 2:
Input: nums = [1,2,3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Example 3:
Input: nums = [2,1,-1]
Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0
Constraints:
1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/
| 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 -= nums[i];
if(leftsum == rightsum) return i;
}
return -1;
}
} | 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];
}
return -1;
}
}; | /**
* @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 (left == right){
return j
}
left += nums[j];
}
return -1
}; | 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 coordinates (0, 0) and its top-right corner point at (li, hi).
Return an integer array count of length points.length where count[j] is the number of rectangles that contain the jth point.
The ith rectangle contains the jth point if 0 <= xj <= li and 0 <= yj <= hi. Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle.
Example 1:
Input: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]
Output: [2,1]
Explanation:
The first rectangle contains no points.
The second rectangle contains only the point (2, 1).
The third rectangle contains the points (2, 1) and (1, 4).
The number of rectangles that contain the point (2, 1) is 2.
The number of rectangles that contain the point (1, 4) is 1.
Therefore, we return [2, 1].
Example 2:
Input: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]
Output: [1,3]
Explanation:
The first rectangle contains only the point (1, 1).
The second rectangle contains only the point (1, 1).
The third rectangle contains the points (1, 3) and (1, 1).
The number of rectangles that contain the point (1, 3) is 1.
The number of rectangles that contain the point (1, 1) is 3.
Therefore, we return [1, 3].
Constraints:
1 <= rectangles.length, points.length <= 5 * 104
rectangles[i].length == points[j].length == 2
1 <= li, xj <= 109
1 <= hi, yj <= 100
All the rectangles are unique.
All the points are unique.
| 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
right = mid
else:
left = mid + 1
return ans
def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:
# Sort rectangles based on the lengths
rectangles.sort()
# Group rectangles by their height in increasing order of their length
lengths = {}
for x,y in rectangles:
if y in lengths:
lengths[y].append(x)
else:
lengths[y] = [x]
heights = sorted(list(lengths.keys()))
count = [0] * len(points)
for idx, point in enumerate(points):
x, y = point
# Get the min height rectangle that would accommodate the y coordinate of current point.
minHeightRectIdx = self.binarySearch(heights, y)
if minHeightRectIdx is not None:
for h in heights[minHeightRectIdx:]:
# Get the Min length rectangle that would accommodate the x coordinate of current point for all h height rectangles.
minLenRectIdx = self.binarySearch(lengths[h], x)
if minLenRectIdx is not None:
count[idx] += len(lengths[h]) - minLenRectIdx
return count | 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 ArrayList<Integer>());
}
rects.get(rect[1]).add(rect[0]);
max = Math.max(max, rect[1]);
}
for(int k : rects.keySet()) {
Collections.sort(rects.get(k));
}
int[] ans = new int[points.length];
for(int i = 0; i < points.length; i++) {
if (points[i][1] > max) {
continue;
}
int count = 0;
for(int key : rects.subMap(points[i][1], max + 1).keySet()) {
List<Integer> y = rects.get(key);
count += binarySearch(y, points[i][0]);
}
ans[i] = count;
}
return ans;
}
private int binarySearch(List<Integer> vals, int val) {
int lo = 0;
int hi = vals.size() - 1;
int id = -1;
while(lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (vals.get(mid) < val) {
lo = mid + 1;
} else {
id = mid;
hi = mid - 1;
}
}
if (id < 0) {
return 0;
}
return vals.size() - id;
}
} | 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)
heights[rect[1]].push_back(rect[0]);
for(i=0;i<101;i++)
sort(heights[i].begin(), heights[i].end());
for(auto point : points)
{
count = 0;
x = point[0];
y = point[1];
for(i=y;i<101;i++)
{
ind = lower_bound(heights[i].begin(), heights[i].end(), x) - heights[i].begin();
count += (heights[i].size() - ind);
}
ans.push_back(count);
}
return ans;
}
}; | 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]; j < 101; j++) {
// lowest index >= point[0]
let index = lower_bound(buckets[j], point[0]);
sum += buckets[j].length - index;
}
res.push(sum);
}
return res;
function lower_bound(arr, targ) {
let low = 0, high = arr.length;
while (low < high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] >= targ) high = mid;
else low = mid + 1;
}
return low;
}
}; | 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: [[1]]
Constraints:
1 <= n <= 8
| # 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 , leftvalues
# are left tree and right val are rightree, then for each number create a tree
# assign the left and right to that root and append the root to the ans
nums = list(range(1,n+1))
def dfs(nums):
if not nums:
return [None]
ans = []
for i in range(len(nums)):
leftTrees = dfs(nums[:i])
rightTrees = dfs(nums[i+1:])
for l in leftTrees:
for r in rightTrees:
root = TreeNode(nums[i])
root.left = l
root.right = r
ans.append(root)
return ans
return dfs(nums) | /**
* 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 Solution {
public List<TreeNode> generateTrees(int n) {
return helper(1,n);
}
public List<TreeNode> helper(int lo, int hi){
List<TreeNode> res=new ArrayList<>();
if(lo>hi){
res.add(null);
return res;
}
for(int i=lo;i<=hi;i++){
List<TreeNode> left=helper(lo,i-1);
List<TreeNode> right=helper(i+1,hi);
for(TreeNode l:left){
for(TreeNode r:right){
TreeNode head=new TreeNode(i);
head.left=l;
head.right=r;
res.add(head);
}
}
}
return res;
}
} | 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++)
{
//don't create node here, bcz for each combination of subtree, node with new address has to be generated
//recursive call for left,right child, they will return vector of all possible subtrees
lChild = solve(start, i-1);
rChild = solve(i+1, end);
//for each subtree returned by lChild, forming combination with each subtree returned by rChild
for(auto l: lChild)
{
for(auto r: rChild)
{
//generating new node for each combination
TreeNode* node = new TreeNode(i);
//attaching left, right childs
node->left = l;
node->right = r;
res.push_back(node);
}
}
}
//returning all possible subtrees
return res;
}
vector<TreeNode*> generateTrees(int n) {
return solve(1, n);
}
}; | 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, i-1);
let right = generateRec(i+1, end);
for(let l = 0; l < left.length; l++){
for(let r = 0; r < right.length; r++){
let root = new TreeNode(i,left[l], right[r]);
result.push(root);
}
}
}
return result;
} | 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 number) Fills the container at index with the number. If there is already a number at that index, replace it.
int find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system.
Example 1:
Input
["NumberContainers", "find", "change", "change", "change", "change", "find", "change", "find"]
[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]
Output
[null, -1, null, null, null, null, 1, null, 2]
Explanation
NumberContainers nc = new NumberContainers();
nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.
nc.change(2, 10); // Your container at index 2 will be filled with number 10.
nc.change(1, 10); // Your container at index 1 will be filled with number 10.
nc.change(3, 10); // Your container at index 3 will be filled with number 10.
nc.change(5, 10); // Your container at index 5 will be filled with number 10.
nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.
nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20.
nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.
Constraints:
1 <= index, number <= 109
At most 105 calls will be made in total to change and find.
| 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[index]:
self.numberIndexes[self.numbersByIndex[index]].remove(index)
self.numbersByIndex[index] = number
self.numberIndexes[number].add(index)
heappush(self.numberIndexesHeap[number], index)
else:
self.numbersByIndex[index] = number
self.numberIndexes[number].add(index)
heappush(self.numberIndexesHeap[number], index)
def find(self, number: int) -> int:
while self.numberIndexesHeap[number] and self.numberIndexesHeap[number][0] not in self.numberIndexes[number]:
heappop(self.numberIndexesHeap[number]) # make sure the smallest index in heap is still an index for number
return self.numberIndexesHeap[number][0] if self.numberIndexesHeap[number] else -1 | 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.put(number,new TreeSet<>());
map.get(number).add(index);
}
public int find(int number) {
if(!map.containsKey(number)) return -1;
for(Integer a:map.get(number)){
if(m.get(a)==number) return a;
}
return -1;
}
} | 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 there is no number at the given index.
numberToIndex[number].insert(index); // store index corresponding to the given number
indexToNumber[index] = number; // store number corresponding to the index.
}
else { // Update both map.
int num = indexToNumber[index]; // number at given index currently.
// remove the index
numberToIndex[num].erase(index);
if (numberToIndex[num].empty()) numberToIndex.erase(num);
// insert the new number at the given index and store the index corresponding to that number.
numberToIndex[number].insert(index);
indexToNumber[index] = number;
}
}
int find(int number) {
if (!numberToIndex.count(number)) return -1;
// returning first element in the set as it will be the smallest index always.
return *numberToIndex[number].begin();
}
}; | 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)
{
this.obj[key].splice(ind, 1);
if(this.obj[number])
this.obj[number].push(index);
else
this.obj[number] = [index];
this.global[index]=1;
return;
}
}
}
if(this.obj[number])
this.obj[number].push(index);
else
this.obj[number] = [index];
this.global[index]=1;
};
NumberContainers.prototype.find = function(number) {
if(this.obj[number])
{
if(this.obj[number].length == 0)
return -1
else
return Math.min(...this.obj[number])
}
return -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","h","o","n","s","r","u","t","w","v","x","z"].
s is guaranteed to be valid.
| 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] = s.count("s") - c[6]
c[9] = s.count("i") - (c[8] + c[5] + c[6])
c[1] = s.count("o") - (c[0] + c[2] + c[4])
c = sorted(c.items(), key = lambda x: x[0])
ans = ""
for k, v in c:
ans += (str(k) * v)
return ans | 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 int[] VALS = new int[] { 0, 2, 8, 6, 3, 7, 4, 1, 5, 9 };
// Maps for checking uniqueness more conveniently:
static final Map<Integer, List<Integer>> ORDERED_FREQ_MAP;
static final Map<Integer, Integer> ORDERED_DIGIT_MAP;
static {
// Initialize our ordered frequency map: 0-25 key to 0-25 values finishing the word:
final LinkedHashMap<Integer, List<Integer>> orderedFreqMap = new LinkedHashMap<>();
// Also initialize a digit lookup map, e.g. 'g' becomes 6 maps to 8 for ei[g]ht:
final LinkedHashMap<Integer, Integer> orderedDigitMap = new LinkedHashMap<>();
for (int i = 0; i < 10; ++i) {
final char unique = UNIQUES[i].charAt(0);
final int ui = convert(unique);
orderedFreqMap.put(ui, converting(UNIQUES[i].substring(1).toCharArray()));
orderedDigitMap.put(ui, VALS[i]);
}
// Let's make sure we aren't tempted to modify these since they're static.
ORDERED_FREQ_MAP = Collections.unmodifiableMap(orderedFreqMap);
ORDERED_DIGIT_MAP = Collections.unmodifiableMap(orderedDigitMap);
}
public String originalDigits(String s) {
// count frequencies of each letter in s:
final int[] freqs = new int[26];
for (int i = 0; i < s.length(); ++i) {
freqs[convert(s.charAt(i))]++;
}
// Crate an array to store digit strings in order, e.g. '00000', '11, '2222222', etc.
final String[] strings = new String[10];
// Iterate through uniqueness checks in order:
for (Map.Entry<Integer, List<Integer>> entry : ORDERED_FREQ_MAP.entrySet()) {
final int index = entry.getKey(); // unique letter in 0-25 form
final int value = ORDERED_DIGIT_MAP.get(index); // corresponding digit, e.g. 8 for 'g', 0 for 'z', etc.
final int count = freqs[index]; // frequency of unique letter = frequency of corresponding digit
if (count > 0) {
// update frequencies to remove the digit's word count times:
freqs[index] -= count;
for (int idx : entry.getValue()) {
freqs[idx] -= count;
}
// now create the digit string for the unique digit: the digit count times:
strings[value] = String.valueOf(value).repeat(count);
} else {
// count 0 - empty strring for this digit
strings[value] = "";
}
}
// append the digit strings in order
final StringBuilder sb = new StringBuilder();
for (String str : strings) {
sb.append(str);
}
// and we are done!
return sb.toString();
}
// Converts a character array into a list of 0-25 frequency values.
private static final List<Integer> converting(char... carr) {
final List<Integer> list = new ArrayList<>();
for (char ch : carr) {
list.add(convert(ch)); // converts each to 0-25
}
return Collections.unmodifiableList(list);
}
// Converts a-z to 0-26. Bitwise AND with 31 gives a=1, z=26, so then subtract one.
private static final Integer convert(char ch) {
return (ch & 0x1f) - 1; // a->0, z->25
}
} | 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]-'a'] > 0 && m[t[2]-'a'] > 0){
int min_o = min({m[t[0]-'a'] ,m[t[1]-'a'] , m[t[2]-'a']});
m[t[0]-'a'] -= min_o;
m[t[1]-'a'] -= min_o;
m[t[2]-'a'] -= min_o;
while(min_o--) ans += (char)(i +'0');
}
}else if(t.length() == 4){
if(m[t[0]-'a'] > 0 && m[t[1]-'a'] > 0 && m[t[2]-'a'] > 0 && m[t[3]-'a'] > 0){
int min_o = min({m[t[0]-'a'] ,m[t[1]-'a'] , m[t[2]-'a'], m[t[3]-'a']});
m[t[0]-'a'] -= min_o;
m[t[1]-'a'] -= min_o;
m[t[2]-'a'] -= min_o;
m[t[3]-'a'] -= min_o;
while(min_o--) ans += (char)(i +'0');
}
}else if(t.length() == 5){
if(m[t[0]-'a'] > 0 && m[t[1]-'a'] > 0 && m[t[2]-'a'] > 0 && m[t[3]-'a'] > 0 && m[t[4]-'a'] > 0){
int min_o = min({m[t[0]-'a'] ,m[t[1]-'a'] , m[t[2]-'a'], m[t[3]-'a'], m[t[4]-'a']});
m[t[0]-'a'] -= min_o;
m[t[1]-'a'] -= min_o;
m[t[2]-'a'] -= min_o;
m[t[3]-'a'] -= min_o;
m[t[4]-'a'] -= min_o;
while(min_o--) ans += (char)(i +'0');
}
}
}
}
string originalDigits(string s) {
string ans;
vector<int> m(26,0);
for(auto x:s) m[x-'a']++;
fun(0,ans,m);
fun(1,ans,m);
sort(ans.begin(),ans.end());
return ans;
}
}; | /**
* @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'
}
const letterToDigits = {}
for(const key in numberToWord) {
const currWord = numberToWord[key]
for(const letter of currWord) {
if(!(letter in letterToDigits)) letterToDigits[letter] = new Set()
letterToDigits[letter].add(key)
}
}
const inputFreqs = {}
for(let i = 0; i < s.length; i++) {
const currChar = s[i]
if(!(currChar in inputFreqs)) inputFreqs[currChar] = 0
inputFreqs[currChar]++
}
const letters = Object.keys(inputFreqs)
const res = dfs(letters[0])
return [...res].sort().join('')
function dfs(currLetter) {
if(!isValid(inputFreqs)) return null
if(getTotalRemaining(inputFreqs) === 0) return []
const possibleDigits = letterToDigits[currLetter]
for(const digit of [...possibleDigits]) {
const wordRepresentation = numberToWord[digit]
subtract(wordRepresentation)
if(!isValid(inputFreqs)) {
addBack(wordRepresentation)
continue
}
const nextLetter = getNext(inputFreqs)
const nextDigits = dfs(nextLetter)
if(nextDigits !== null) return [digit] + nextDigits
addBack(wordRepresentation)
}
return null
}
function isValid(inputFreqs) {
for(const key in inputFreqs) {
const count = inputFreqs[key]
if(count < 0) return false
}
return true
}
function getTotalRemaining(inputFreqs) {
let sum = 0
for(const key in inputFreqs) {
const count = inputFreqs[key]
sum += count
}
return sum
}
function subtract(word) {
for(const char of word) {
if(!(char in inputFreqs)) inputFreqs[char] = 0
inputFreqs[char]--
}
}
function addBack(word) {
for(const char of word) {
inputFreqs[char]++
}
}
function getNext(inputFreqs) {
for(const key in inputFreqs) {
const count = inputFreqs[key]
if(count > 0) return key
}
return null
}
}; | 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 right).
For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).
Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.
Example 1:
Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
Output: true
Explanation: The node values on each level are:
Level 0: [1]
Level 1: [10,4]
Level 2: [3,7,9]
Level 3: [12,8,6,2]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
Example 2:
Input: root = [5,4,2,3,3,7]
Output: false
Explanation: The node values on each level are:
Level 0: [5]
Level 1: [4,2]
Level 2: [3,3,7]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
Example 3:
Input: root = [5,9,1,3,5,7]
Output: false
Explanation: Node values in the level 1 should be even integers.
Constraints:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 106
| 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:
prev = 0
for _ in range(len(queue)):
currNode = queue.popleft()
comparison = {0:prev < currNode.val, 1:prev > currNode.val}
if currNode.val % 2 != evenOddLevel[level % 2]:
return False
else:
if prev != 0 and comparison[level % 2]:
prev = currNode.val
elif prev == 0:
prev = currNode.val
else:
return False
if currNode.left:
queue.append(currNode.left)
if currNode.right:
queue.append(currNode.right)
level += 1
return True | 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 prev with 0 to check strictly increasing and Integer_MAX_VALUE to check strictly decreasing
while(size-->0){
TreeNode rem = qu.remove();
if(even){
if(rem.val%2==0 || rem.val<=prev){ // false if value at even level is even or not strictly increasing
return false;
}
}else{
if(rem.val%2!=0 || rem.val>=prev){// false if value at odd level is odd or not strictly decreasing
return false;
}
}
if(rem.left!=null){
qu.add(rem.left);
}
if(rem.right!=null){
qu.add(rem.right);
}
prev=rem.val; //update previous
}
even = !even; //change level
}
return true;
}
} | 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++)
{ TreeNode* t=q.front();q.pop();
v.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
if(j%2==0)
{
for(int k=0;k<v.size()-1;k++)
{
if(v[k]%2==0)
return false;
if(v[k]>=v[k+1])
return false;
}
if(v[v.size()-1]%2==0)
return false;
}
else
{
for(int k=0;k<v.size()-1;k++)
{
if(v[k]%2==1)
return false;
if(v[k]<=v[k+1])
return false;
}
if(v[v.size()-1]%2==1)
return false;
}
j++;
ans.push_back(v);
}
return true;
}
}; | /**
* 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 = function(root) {
let queue = [root];
let steps = 0;
while(queue.length>0){
const currLength = queue.length;
let nextQueue=[];
for(let i=0; i<currLength;i++){
const node = queue[i];
if(steps%2 !== 0){
if((i<currLength-1 && node.val<=queue[i+1].val) || node.val%2 !== 0){
return false;
}
}else if((i<currLength-1 && node.val>=queue[i+1].val)|| node.val%2 === 0){
return false;
}
if(node.left) nextQueue.push(node.left);
if(node.right) nextQueue.push(node.right);
}
queue = nextQueue;
steps++;
}
return true;
}; | 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
Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].
Example 2:
Input: n = 1, primes = [2,3,5]
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].
Constraints:
1 <= n <= 105
1 <= primes.length <= 100
2 <= primes[i] <= 1000
primes[i] is guaranteed to be a prime number.
All the values of primes are unique and sorted in ascending order.
| 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] == primes[k]*ret[index[k]]:
index[k]+= 1
return ret[-1] | //---------------------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 Pair(primes[i],1,primes[i]));
}
for(int i=2;i<=n;){
Pair curr=pq.remove();
if(curr.val!=dp[i-1]){
dp[i]=curr.val;
i++;
}
int newval=curr.prime*dp[curr.ptr+1];
if(newval>0){
pq.add(new Pair(curr.prime, curr.ptr+1,newval));
}
}
return dp[n];
}
}
class Pair implements Comparable<Pair>{
int prime;
int ptr;
int val;
public Pair(int prime, int ptr, int val){
this.prime=prime;
this.ptr=ptr;
this.val=val;
}
public int compareTo(Pair o){
return this.val-o.val;
}
}
//-----------------------O(nk)---------------------------
// class Solution {
// public int nthSuperUglyNumber(int n, int[] primes) {
// int []dp=new int[n+1];
// dp[1]=1;
// int []ptr=new int[primes.length];
// Arrays.fill(ptr,1);
// for(int i=2;i<=n;i++){
// int min=Integer.MAX_VALUE;
// for(int j=0;j<ptr.length;j++){
// int val=dp[ptr[j]]*primes[j];
// if(val>0){
// min=Math.min(min,val);
// }
// }
// dp[i]=min;
// for(int j=0;j<ptr.length;j++){
// int val=dp[ptr[j]]*primes[j];
// if(val>0 && min==val){
// ptr[j]++;
// }
// }
// }
// return dp[n];
// }
// } | 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=INT_MAX;
for(int j=0;j<n1;j++){
x=min(x,primes[j]*dp[p[j]]);
}
dp[i]=x;
for(int j=0;j<n1;j++){
if(x==primes[j]*dp[p[j]])
p[j]++;
}
}
return dp[n-1];
}
}; | 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 (let i=0;i< table.length; i++) {
if (curr === res[table[i]]*primes[i]) table[i]++;
}
res[j] = curr;
}
return res[n-1];
}; | 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" + "7"
- (1, 0): "7" + "777"
- (2, 3): "77" + "77"
- (3, 2): "77" + "77"
Example 2:
Input: nums = ["123","4","12","34"], target = "1234"
Output: 2
Explanation: Valid pairs are:
- (0, 1): "123" + "4"
- (2, 3): "12" + "34"
Example 3:
Input: nums = ["1","1","1"], target = "11"
Output: 6
Explanation: Valid pairs are:
- (0, 1): "1" + "1"
- (1, 0): "1" + "1"
- (0, 2): "1" + "1"
- (2, 0): "1" + "1"
- (1, 2): "1" + "1"
- (2, 1): "1" + "1"
Constraints:
2 <= nums.length <= 100
1 <= nums[i].length <= 100
2 <= target.length <= 100
nums[i] and target consist of digits.
nums[i] and target do not have leading zeros.
| 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();
String a = "", b= "";
for (int i = 1; i<n; i++){
a = target.substring(0,i);
b = target.substring(i,n);
if (map.containsKey(a) && map.containsKey(b)){
if (a.equals(b)) ans += (map.get(a) * (map.get(a)-1));
else ans+= (map.get(a) * map.get(b));
}
}
return ans;
}
} | 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) {
if (s + s == target)
res += frq*(frq-1);
else
res += frq * freq[target.substr(s.size())];
}
}
return res;
}
}; | /**
* @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;
if (x == y) {
count -= 1;
}
}
}
x++;
}
return count;
}; | 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 = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.
Return an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.
Example 1:
Input: arr = [3,2,4,1]
Output: [4,2,4,3]
Explanation:
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = [3, 2, 4, 1]
After 1st flip (k = 4): arr = [1, 4, 2, 3]
After 2nd flip (k = 2): arr = [4, 1, 2, 3]
After 3rd flip (k = 4): arr = [3, 2, 1, 4]
After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.
Example 2:
Input: arr = [1,2,3]
Output: []
Explanation: The input is already sorted, so there is no need to flip anything.
Note that other answers, such as [3, 3], would also be accepted.
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= arr.length
All integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length).
| 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):
#base case where all the numbers are sorted, thus no more recursive calls
if i < 0:
return []
ret = []
#find the biggest number, which always will be the len(arr), or i + 1
idx = arr.index(i + 1)
# if the biggest number is in the right place, as in idx == i, then we don't change anything, but just move to sort the next biggest number
if idx == i:
return sort(i - 1)
#we flip it with the first element (even if the biggest number is the first element, it will flip itself (k = 1) and does not affect the result
ret.append(idx + 1)
flip(0, idx)
#we know the biggest number is the first element of the array. Flip the whole array in the boundary so that the biggest number would be in the last of the subarray (notice not len(arr) - 1 because that will flip the already-sorted elements as well)
ret.append(i + 1)
flip(0, i)
#sort the next biggest number by setting a new boundary i - 1
return ret + sort(i - 1)
return sort(len(arr) - 1)
| // 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;
while(n!=1) {
int maxIndex = findIndex(arr,n);
reverse(arr, maxIndex);
reverse(arr, n-1);
list.add(maxIndex+1);
list.add(n);
n--;
}
return list;
}
static int findIndex(int[] arr, int value) {
for(int i=0; i<arr.length; i++) {
if(arr[i] == value){
return i;
}
}
return 0;
}
static void reverse(int[] arr, int maxIndex) {
int l = 0;
while(l<maxIndex) {
int temp = arr[l];
arr[l] = arr[maxIndex];
arr[maxIndex] = temp;
l++;
maxIndex--;
}
}
} | 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;
vector<int>ans;
while(end>0){
if(arr[end]!=copy[end]){
int pos=end-1;
while(arr[pos]!=copy[end]){
pos--;
}
reverse(arr,0,pos);
if(pos!=0){
ans.push_back(pos+1);
}
reverse(arr,0,end);
ans.push_back(end+1);
}
end--;
}
return ans;
}
}; | 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 it in front of the array
res.push(idx+1);
arr = arr.slice(idx+1);
arr = pancake.concat(arr);//value i is now at index 0
pancake = arr.slice(0,i).reverse();//flip the array with k = i-1 to put the value at its place
res.push(i);
arr = arr.slice(i);
arr = pancake.concat(arr);//now the array is sorted from i to n
}
}
return res;
}; | 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".
Example 2:
Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".
Example 3:
Input: words = ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.
Constraints:
2 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i] consists only of lowercase English letters.
| 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):
if check(words[i], words[j]):
Max = max(Max, len(words[i])*len(words[j]))
return Max | 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++)
for (int j=i+1; j<n; j++)
if ((masks[i] & masks[j]) == 0)
largest = Math.max(largest, words[i].length() * words[j].length());
return largest;
}
} | 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);
}
for(int i = 0;i<words.size();i++){
for(int j =0;j<i;j++){
bool flag = false;
for(auto val : st[i]){
if(st[j].find(val) != st[j].end()){
flag = true;
break;
}
}
if(flag == false) {
int prd = words[i].length() * words[j].length();
res =max(res, prd);
}
}
}
return res;
}
}; | /**
* @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 idx = w.charCodeAt(0) - 'a'.charCodeAt(0);
alpha[idx] = 1;
}
m.set(word, parseInt(alpha.join(''), 2));
}
const hasCommonLetters = (a, b) => {
const sb = m.get(b);
const sa = m.get(a);
return (sa & sb) != 0;
}
let ans = 0, len = words.length;
for(let i = 0; i < len; i++) {
for(let j = i + 1; j < len; j++) {
if(!hasCommonLetters(words[i], words[j])) {
ans = Math.max(ans, words[i].length * words[j].length);
}
}
}
return ans;
}; | 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.right.val) always holds.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
Input: root = [2,2,5,null,null,5,7]
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: root = [2,2,2]
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
Constraints:
The number of nodes in the tree is in the range [1, 25].
1 <= Node.val <= 231 - 1
root.val == min(root.left.val, root.right.val) for each internal node of the tree.
| # 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=deque([root])
while a:
node=a.popleft()
if node.valtemp1:
if node.val | 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 == root.val) go(root.left);
else {
x = false;
ans = Math.min(ans, root.left.val);
}
}
if (root.right != null) {
if (root.right.val == root.val) go(root.right);
else {
x = false;
ans = Math.min(ans, root.right.val);
}
}
}
} | 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.front()->right){
q.push(q.front()->right);
}
q.pop();
}
sort(v.begin(),v.end());
int ans=-1;
for(int i=1;i<v.size();i++){
if(v[i]!=v[0]){
return v[i];
}
}
return ans;
}
}; | 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 if(node.val<=secondMin){
secondMin=node.val
}
if(node.left)que.push(node.left)
if(node.right)que.push(node.right)
}
return secondMin===Math.min()?-1:secondMin
}; | 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,null,2]
Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false
Constraints:
The number of nodes in both trees is in the range [0, 100].
-104 <= Node.val <= 104
| 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 || q == null || p.val != q.val) {
return false;
}
// Recursively check if the left and right subtrees are identical
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
} | 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;
}
stack.push(node1.left, node2.left, node1.right, node2.right);
}
return true;
}; | 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 two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 105
1 <= position[i] <= 109
All integers in position are distinct.
2 <= m <= position.length
| 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):
positions.sort()
low = 0
high = positions [-1]
ans = 0
while low<=high:
distance = low+(high-low)//2
if self.possible(distance,positions,M):
ans = distance
low=distance+1
else:
high=distance-1
return ans | 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];
int ans=-1;
while(low<=high){
int mid=low+(high-low)/2;
if(blackbox(mid,position,m)){
ans=mid;
low=mid+1;
}
else{
high=mid-1;
}
}
return ans;
}
public boolean blackbox(int maxPossibleDist,int[] position, int m){
int balls=1;
int prevballplace=position[0];
for(int i=1;i<position.length;i++){
if(position[i]-prevballplace>=maxPossibleDist){
prevballplace=position[i];
balls++;
}
}
if(balls>=m){
return true;
}
return false;
}
} | 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];
}
}
return basketCount>=m;
}
int maxDistance(vector<int>& position, int m) {
sort(position.begin(),position.end());
int n=position.size();
long long int start=1;
long long int end=position[n-1]-position[0];
int ans=0;
int mid= start+(end-start)/2;
while(start<=end){
if(isPossible(position,m,mid)){
ans=mid;
start=mid+1;
}
else
end=mid-1;
mid= start+(end-start)/2;
}
return ans;
}
}; | 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) {
count++;
dist = 0;
}
}
return count >= m;
}
let left = 1;
let right = position[position.length - 1] - position[0];
let ans;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (canDistribute(mid)) {
ans = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return ans;
}; | 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 list nestedList.
int next() Returns the next integer in the nested list.
boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return res
If res matches the expected flattened list, then your code will be judged as correct.
Example 1:
Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
Example 2:
Input: nestedList = [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
Constraints:
1 <= nestedList.length <= 500
The values of the integers in the nested list is in the range [-106, 106].
| 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 self.flattened_lst[self.idx-1]
def hasNext(self) -> bool:
return self.idx < len(self.flattened_lst)
def flattenList(self, lst):
flattened_lst = []
for ele in lst:
if ele.isInteger():
flattened_lst.append(ele.getInteger())
else:
flattened_lst.extend(self.flattenList(ele.getList()))
return flattened_lst | 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(nested.getList());
}
}
public NestedIterator(List<NestedInteger> nestedList) {
flatten(nestedList);
}
int index=0;
@Override
public Integer next() {
return list.get(index++);
}
@Override
public boolean hasNext() {
return index<list.size();
}
} | 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());
}
else
{
helper(nestedList[i].getList(), v);
}
}
}
public:
NestedIterator(vector<NestedInteger> &nestedList) {
helper(nestedList, v);
index = 0;
}
int next() {
return v[index++];
}
bool hasNext() {
if (v.size() <= index)
{
return false;
}
return true;
}
}; | /**
* // 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 = function() {
* ...
* };
*
* Return the single integer that this NestedInteger holds, if it holds a single integer
* Return null if this NestedInteger holds a nested list
* @return {integer}
* this.getInteger = function() {
* ...
* };
*
* Return the nested list that this NestedInteger holds, if it holds a nested list
* Return null if this NestedInteger holds a single integer
* @return {NestedInteger[]}
* this.getList = function() {
* ...
* };
* };
*/
/**
* @constructor
* @param {NestedInteger[]} nestedList
*/
var NestedIterator = function(nestedList) {
this.nestedList = []
this.ptr = 0
const dfs = (elem) => {
if(!elem.isInteger()) {
let list = elem.getList()
for(let i = 0;i<list.length;i++) {
dfs(list[i])
}
}else {
this.nestedList.push(elem.getInteger())
}
}
for(let i = 0;i<nestedList.length;i++) {
dfs(nestedList[i])
}
};
/**
* @this NestedIterator
* @returns {boolean}
*/
NestedIterator.prototype.hasNext = function() {
if(this.ptr < this.nestedList.length) return true
else return false
};
/**
* @this NestedIterator
* @returns {integer}
*/
NestedIterator.prototype.next = function() {
return this.nestedList[this.ptr++]
};
/**
* Your NestedIterator will be called like this:
* var i = new NestedIterator(nestedList), a = [];
* while (i.hasNext()) a.push(i.next());
*/ | 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 <= 105
1 <= nums[i] <= n
Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
| 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) {
nums[indx] = nums[indx]*-1;
}
}
// 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++) {
if(nums[i]>0) {
res.add(i+1);
}else {
nums[i] *= -1;
}
}
// [ 5, 6]
return res;
}
} | 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 < n; i++) {
if (nums[i] > 0)
res.push_back(i + 1);
}
return res;
}
}; | 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.
Example 1:
Input: s = "abbca"
Output: 28
Explanation: The following are the substrings of "abbca":
- Substrings of length 1: "a", "b", "b", "c", "a" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.
- Substrings of length 2: "ab", "bb", "bc", "ca" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.
- Substrings of length 3: "abb", "bbc", "bca" have an appeal of 2, 2, and 3 respectively. The sum is 7.
- Substrings of length 4: "abbc", "bbca" have an appeal of 3 and 3 respectively. The sum is 6.
- Substrings of length 5: "abbca" has an appeal of 3. The sum is 3.
The total sum is 5 + 7 + 7 + 6 + 3 = 28.
Example 2:
Input: s = "code"
Output: 20
Explanation: The following are the substrings of "code":
- Substrings of length 1: "c", "o", "d", "e" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.
- Substrings of length 2: "co", "od", "de" have an appeal of 2, 2, and 2 respectively. The sum is 6.
- Substrings of length 3: "cod", "ode" have an appeal of 3 and 3 respectively. The sum is 6.
- Substrings of length 4: "code" has an appeal of 4. The sum is 4.
The total sum is 4 + 6 + 6 + 4 = 20.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
| 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) * (long) (n - i);
pos[j] = i;
}
return res;
}
} | 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(int i=0;i<n;i++)
{
if(s[i] == ch) prev = i+1; // if the current character is equal to ch , then the no. of substring
// ending at i and having at least one occurence of ch will be i+1 .
ans+=prev; // else the no. of substrings ending at i and having at least
// one occurence of ch will be the equal to, the previous index of ch.
}
}
return ans; // TC - O(n*26) , SC - O(1)
}
}; | 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,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity? | 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 back elements it covers in i;
if(nums[i] + nums[j] == target) {
// Check sum == target or not
answer[0] = i;
answer[1] = j;
return answer;
}
}
}
return null;
}
} | 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};
}
}
}
return {}; // No solution found
}
}; | /**
* @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.push(i, j);
found = 1;
break;
}
}
if(found == 1) return sol;
}
return 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, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Example 2:
Input: nums = [4,14,4]
Output: 4
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 109
The answer for the given input will fit in a 32-bit integer.
| 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];
cnt[idx][j]++;
}
}
return total;
}
} | /*
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 number of ones in the XOR of those two elements
the intuition behind this method is that XOR will contain 1's at those places
where the corresponding bits of elements x & y are different
therefore we will add this count
to our answer
*/
class Solution {
public:
int hammingDistance(int x, int y) {
int XOR=x^y;
int count=0;
while(XOR){
if(XOR&1)
count++;
XOR=XOR>>1;
}
return count;
}
int totalHammingDistance(vector<int>& nums) {
int ans=0;
for(int i=0;i<nums.size()-1;i++){
for(int j=i+1;j<nums.size();j++){
ans+=hammingDistance(nums[i],nums[j]);
}
}
return ans;
}
}; | 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,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
Output: [0,1,2,1000000,1000001,1000002,5]
Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
Example 2:
Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
Explanation: The blue edges and nodes in the above figure indicate the result.
Constraints:
3 <= list1.length <= 104
1 <= a <= b < list1.length - 1
1 <= list2.length <= 104
| 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:
head = head.next
if cur.next:
head.next = cur.next
return list1 | 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;
left.next = list2;
while (list2.next != null)
list2 = list2.next;
list2.next = middle.next;
return list1;
}
} | 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
int jump2 = 1;
ListNode *temp2 = list1;
while(jump2 <= b){
temp2 = temp2->next;
jump2++;
} //Gets the pointer to b
ListNode *temp3=list2;
while(temp3->next != NULL){
temp3=temp3->next;
} //Gets the pointer to the tail of list2
temp1->next=list2; //set the next pointer of a to the head of list2
temp3->next = temp2->next; //set next of tail of list2 to the pointer to b
return list1; //return the original list i.e. list1
}
}; | 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 = tail.next;
}
start.next = list2;
tail.next = end;
return list1;
}; | 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 to maximize its total capital after finishing at most k distinct projects.
You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.
Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.
The answer is guaranteed to fit in a 32-bit signed integer.
Example 1:
Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
Output: 4
Explanation: Since your initial capital is 0, you can only start the project indexed 0.
After finishing it you will obtain profit 1 and your capital becomes 1.
With capital 1, you can either start the project indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
Example 2:
Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]
Output: 6
Constraints:
1 <= k <= 105
0 <= w <= 109
n == profits.length
n == capital.length
1 <= n <= 105
0 <= profits[i] <= 104
0 <= capital[i] <= 109
| 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))]
projects.sort(key=lambda x: x[0])
heap = []
for i in range(k):
while projects and projects[0][0] <= w:
heappush(heap, -1*projects.pop(0)[1])
if not heap:
break
p = -heappop(heap)
w += p
return w | 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[] capital) {
if (k == 0 || i >= profits.length)
return 0;
if (dp[k][i] != -1)
return dp[k][i];
int res = Integer.MIN_VALUE;
if (capital[i] <= w) {
res = Math.max(res, Math.max(profits[i] + help(k - 1, w + profits[i], i + 1, profits, capital),
help(k, w, i + 1, profits, capital)));
} else {
res = Math.max(res, help(k, w, i + 1, profits, capital));
}
return dp[k][i] = res;
}
} | 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++)
{
//int val = profit[i]-capital[i];
if(capital[i] <= w)
{
pqgs.push({profits[i],capital[i]});
}
else if(capital[i] > w)
{
pqsg.push({capital[i],profits[i]});
}
}
while(k-- && !pqgs.empty())
{
pair<int, int> tmp = pqgs.top();
w += tmp.first;
pqgs.pop();
while(!pqsg.empty() && pqsg.top().first <= w)
{
pqgs.push({pqsg.top().second,pqsg.top().first});
pqsg.pop();
}
}
return w;
}
}; | 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++) {
while (!capitals_asc_queue.isEmpty() && capitals_asc_queue.front().element[0] <=w ) {
let el = capitals_asc_queue.dequeue().element;
profits_desc_queue.enqueue(el, el[1]);
}
if (profits_desc_queue.isEmpty()) return w;
w += profits_desc_queue.dequeue().element[1];
}
return w;
} | 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 $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.
However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.
Implement the ATM class:
ATM() Initializes the ATM object.
void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500.
int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).
Example 1:
Input
["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"]
[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]
Output
[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]
Explanation
ATM atm = new ATM();
atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,
// and 1 $500 banknote.
atm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote
// and 1 $500 banknote. The banknotes left over in the
// machine are [0,0,0,2,0].
atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.
// The banknotes in the machine are now [0,1,0,3,1].
atm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote
// and then be unable to complete the remaining $100,
// so the withdraw request will be rejected.
// Since the request is rejected, the number of banknotes
// in the machine is not modified.
atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote
// and 1 $500 banknote.
Constraints:
banknotesCount.length == 5
0 <= banknotesCount[i] <= 109
1 <= amount <= 109
At most 5000 calls in total will be made to withdraw and deposit.
At least one call will be made to each function withdraw and deposit.
| 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 = []
for val, n in zip(self.values[::-1], self.cash[::-1]):
need = min(n, amount // val)
res = [need] + res
amount -= (need * val)
if amount == 0:
self.deposit([-x for x in res])
return res
else:
return [-1] | 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.
}
public void deposit(int[] banknotesCount) {
for(int i = 0; i < banknotesCount.length; i++){
notes[i] += banknotesCount[i]; // add new deposit money to existing
}
}
public int[] withdraw(int amount) {
int[] result = new int[5]; // create result array to store quantity of each notes we will be using to withdraw "amount"
for(int i = 4; i >= 0; i--){
if(amount >= denoms[i] ){
int quantity = (int) Math.min(notes[i], amount / denoms[i]); // pick the minimum quanity. because if say, amount/denoms[i] gives 3 but you only have 1 note. so you have to use 1 only instead of 3
amount -= denoms[i] * quantity; // amount left = 100
result[i] = quantity;
}
}
if(amount != 0){ return new int[]{-1}; }
for(int i = 0; i < 5; i++){ notes[i] -= result[i]; } // deduct the quantity we have used.
return result;
}
} | 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) {
take[i] = min(bank[i], amount / val[i]);
amount -= take[i] * val[i];
}
if (amount)
return { -1 };
for (int i = 0; i < 5; ++i)
bank[i] -= take[i];
return take;
}
}; | 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]
}
return this.bankNotes
};
/**
* @param {number} amount
* @return {number[]}
*/
ATM.prototype.withdraw = function(amount) {
let remain = amount
let usedBankNotes = new Array(5).fill(0)
let temp = [...this.bankNotes]
for (let i = 4; i >= 0; i--) {
if (temp[i] > 0 && remain >= this.banksNotesValue[i]) {
const bankNote = Math.floor(remain / this.banksNotesValue[i])
const maxCanUse = Math.min(temp[i], bankNote)
usedBankNotes[i] = maxCanUse
temp[i] -= maxCanUse
remain -= maxCanUse * this.banksNotesValue[i]
}
}
if (remain > 0) {
return [-1]
} else {
this.bankNotes = temp
return usedBankNotes
}
};
/**
* Your ATM object will be instantiated and called as such:
* var obj = new ATM()
* obj.deposit(banknotesCount)
* var param_2 = obj.withdraw(amount)
*/ | 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 boundary of the grid in any number of moves.
Example 1:
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
Example 2:
Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation: All 1s are either on the boundary or can reach the boundary.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j] is either 0 or 1.
| 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)
self.recursion(grid, row, col-1, m, n)
def numEnclaves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
if not m or not n:
return 0
# mark all boundary lands and neighbors with 0
for row in range(m):
self.recursion(grid, row, 0, m, n)
self.recursion(grid, row, n-1, m, n)
for col in range(n):
self.recursion(grid, 0, col, m, m)
self.recursion(grid, m-1, col, m, n)
result = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
result += 1
return result | 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] ==0)
{
continue;
}
if(i==0||i==grid.length-1||j==grid[0].length-1||j==0)
{
dfs(grid,i,j);
}
}
}
int count = 0;
for(int i = 0;i<grid.length;i++)
{
for(int j = 0;j<grid[0].length;j++)
{
if(grid[i][j]==1)
{
count++;
}
}
}
return count;
}
int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
public void dfs(int[][] grid,int row,int col) {
grid[row][col] = 0;
for(int k = 0;k<4;k++)
{
int rowdash = row+dirs[k][0];
int coldash = col+dirs[k][1];
if(rowdash<0||coldash<0||rowdash>=grid.length||coldash>=grid[0].length||
grid[rowdash][coldash]==0)
{
continue;
}
if(grid[rowdash][coldash]==1)
{
dfs(grid,rowdash,coldash);
}
}
}
} | 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==grid.size()-1 || j==grid[0].size()-1))
{
queue<vector<int>> q;
q.push({i,j});
while(!q.empty())
{
vector<int> a;
a=q.front();
q.pop();
grid[a[0]][a[1]]=0;
if(a[0]+1<grid.size() && grid[a[0]+1][a[1]]==1)
{
q.push({a[0]+1,a[1]});
grid[a[0]+1][a[1]]=0;
}
if(a[1]+1<grid[0].size() && grid[a[0]][a[1]+1]==1)
{
q.push({a[0],a[1]+1});
grid[a[0]][a[1]+1]=0;
}
if(a[0]-1>=0 && grid[a[0]-1][a[1]]==1)
{
q.push({a[0]-1,a[1]});
grid[a[0]-1][a[1]]=0;
}
if(a[1]-1>=0 && grid[a[0]][a[1]-1]==1)
{
q.push({a[0],a[1]-1});
grid[a[0]][a[1]-1]=0;
}
}
}
}
}
int m=0;
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[0].size();j++)
{
m+=grid[i][j];
}
}
return m;
}
}; | /**
* @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)
updateBoundaryLand(row - 1,col)
updateBoundaryLand(row,col + 1)
updateBoundaryLand(row,col - 1)
}
}
for(let i=0;i<rowLength;i++){
if(grid[i][0] || grid[i][colLength-1]){
updateBoundaryLand(i,0)
updateBoundaryLand(i,colLength-1)
}
}
for(let j=0;j<colLength;j++){
if(grid[0][j] || grid[rowLength-1][j]){
updateBoundaryLand(0,j)
updateBoundaryLand(rowLength-1,j)
}
}
for(let i=0;i<rowLength;i++){
for(let j=0;j<colLength;j++){
if(grid[i][j]) count++
}
}
return count
}; | 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 are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal).
A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below:
Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal.
Example 1:
Input: board = [[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],["W","B","B",".","W","W","W","B"],[".",".",".","B",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."]], rMove = 4, cMove = 3, color = "B"
Output: true
Explanation: '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.
The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.
Example 2:
Input: board = [[".",".",".",".",".",".",".","."],[".","B",".",".","W",".",".","."],[".",".","W",".",".",".",".","."],[".",".",".","W","B",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".","B","W",".","."],[".",".",".",".",".",".","W","."],[".",".",".",".",".",".",".","B"]], rMove = 4, cMove = 4, color = "W"
Output: false
Explanation: While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.
Constraints:
board.length == board[r].length == 8
0 <= rMove, cMove < 8
board[rMove][cMove] == '.'
color is either 'B' or 'W'.
| 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 range(8):
r, c = rMove + moves[d][0], cMove + moves[d][1]
if 0 <= r < 8 and 0 <= c < 8 and board[r][c] == opposite_color:
directions[d] = True
for step in range(2, 8):
if not any(d for d in directions):
return False
for d in range(8):
if directions[d]:
r, c = rMove + step * moves[d][0], cMove + step * moves[d][1]
if 0 <= r < 8 and 0 <= c < 8:
if board[r][c] == color:
return True
elif board[r][c] == ".":
directions[d] = False
else:
directions[d] = False
return False | 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;
}
return false;
}
public boolean dfs(char[][] board, int r, int c, char color,int[] direcn,int len)
{
int nr = r + direcn[0];
int nc = c + direcn[1];
if( nr<0 || nc<0 || nr>7 || nc>7) return false;
if(board[nr][nc] == color)
{
if(len>=2) return true;
else
return false;
}
else
{
if(board[nr][nc] == '.')
{
return false;
}
return dfs(board,nr,nc,color,direcn,len+1);
}
}
} | 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 == 'W') return board[x][y] == 'B';
return false;
}
bool checkMove(vector<vector<char>>& board, int rMove, int cMove, char color) {
vector<int> dir_x = {0, 0, 1, 1, 1, -1, -1, -1}, dir_y = {1, -1, 1, -1, 0, 1, -1, 0};
for (int i = 0; i < 8; i++) {
int x = rMove + dir_x[i], y = cMove + dir_y[i], count = 0;
while (inBoard(board, x, y) && isLegal(board, x, y, color)) {
x += dir_x[i], y += dir_y[i];
count++;
}
if (inBoard(board, x, y) && board[x][y] == color && count > 0) return true;
}
return false;
}
}; | 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];
if (isLegal(rMove, cMove, rowDir, colDir, color, 1)) return true;
}
}
return false;
function withinBound(row, col) {
return row >= 0 && col >= 0 && row < 8 && col < 8;
}
function isLegal(currRow, currCol, rowDir, colDir, startColor, length) {
if (!withinBound(currRow, currCol)) return false; // we went passed the boundaries
if (board[currRow][currCol] === startColor) return length >= 3; // we seen another start color
if (board[currRow][currCol] === "." && length > 1) return false;
return isLegal(currRow + rowDir, currCol + colDir, rowDir, colDir, startColor, length + 1);
}
}; | 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 can Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
Example 1:
Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
Example 2:
Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1
Constraints:
1 <= envelopes.length <= 105
envelopes[i].length == 2
1 <= wi, hi <= 105
| 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)
else:
rst[i] = h
return len(rst) | 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 of LIS
ArrayList<Integer> tempList = new ArrayList<>();
tempList.add(envelopes[0][1]);
for(int i=1; i<envelopes.length; i++){
if(envelopes[i][1]>tempList.get(tempList.size()-1)){
tempList.add(envelopes[i][1]);
} else{
//if the element is smaller than the largest(last because it is sorted) element of tempList, replace the largest smaller element of tempList with it..
//ex->(assume if envelopes[i][1] is 4), then >>[1,7,8] will become [1,4,8]<<
int index = lowerBound(tempList, envelopes[i][1]);
tempList.set(index, envelopes[i][1]);
}
}
return tempList.size();
}
//finding the index of greatest smaller element
public int lowerBound(ArrayList<Integer> list, int search){
int start = 0;
int end = list.size()-1;
while(start<end){
int mid = start + (end-start)/2;
if(list.get(mid) < search){
start = mid+1;
} else{
end = mid;
}
}
return start;
}
}
class sortEnvelopes implements Comparator<int[]> {
public int compare(int[] a, int[] b){
if(a[0] == b[0]){
//to ignore the duplicates, we are sorting such that, for same width-> element with
//largest height would be considered first, in this way all the other smaller heights would
//be ignored
return b[1] - a[1];
} else{
return a[0] - b[0];
}
}
} | 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& cur: envelopes)
{
if(len==0 || envelopes[len-1][1] < cur[1])
envelopes[len++] = cur;
else
*lower_bound(envelopes.begin(), envelopes.begin()+ len, cur, [](auto &l, auto &r)
{
return l[1] < r[1];
}) = cur;
}
return len;
}
}; | 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 {
right = mid - 1;
}
}
return left;
}
var maxEnvelopes = function(envelopes) {
envelopes.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]);
const sub = [envelopes[0][1]];
for (let envelope of envelopes) {
if (envelope[1] > sub[sub.length - 1]) {
sub.push(envelope[1]);
} else {
const replaceIndex = binarySearch(sub, envelope[1]);
sub[replaceIndex] = envelope[1];
}
}
return sub.length;
}; | Russian Doll Envelopes |