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 |
|---|---|---|---|---|---|
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n... | class Solution:
def winnerSquareGame(self, n: int) -> bool:
squares = lambda x: (i * i for i in range(isqrt(x), 0, -1))
@cache
def can_win(n: int) -> bool:
return n and not all(can_win(n - s) for s in squares(n))
return can_win(n) | class Solution {
// idea: Alice wins a game with n stones if and only if there exists
// some perfect square p <= n such that Alice wins a game with
// n - p stones... i.e., Bob DOES NOT win a game with n - p stones
public boolean winnerSquareGame(int n) {
// this bit would be better with just a... | class Solution {
public:
bool winnerSquareGame(int n) {
vector<int> dp(n+1,false);
for(int i=1;i<=n;i++){
for(int j=sqrt(i);j>=1;j--){
if(dp[i-j*j] == false){
dp[i] = true;
break;
}
}
}
... | var winnerSquareGame = function(n) {
const map = new Map();
map.set(0, false);
map.set(1, true);
const dfs = (num) => {
if( map.has(num) ) return map.get(num);
let sqRoot = Math.floor(Math.sqrt(num));
for(let g=1; g<=sqRoot; g++){
if( !dfs(num - (g*... | Stone Game IV |
In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1).
In one move th... | class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
queue , vis , n = [(0,1,0,0)] , {} , len(grid)
while queue:
x,y,pos,moves = queue.pop(0)
if x == y == n-1 and pos == 0: return moves
if pos == 0:
if y + 1 < n and grid[x][y+1] ==... | class Solution {
public int minimumMoves(int[][] grid) {
int n = grid.length;
//boolean[][][][] visited = new boolean[n][n][n][n];
Set<Position> set = new HashSet<>();
Queue<Position> q = new LinkedList<>();
q.offer(new Position(0,0,0,1));
i... | class Solution {
public:
int n;
set<vector<int>> visited;
bool candown(vector<vector<int>>& grid,int x,int y,bool hor){
if(!hor){
if(x+2<n && grid[x+1][y]==0 && grid[x+2][y]==0 && !visited.count({x+1,y,hor})){
return true;
}
}else{
if(x+1<n && y+1<n && grid[x+1][y]==0 && gr... | /**
* @param {number[][]} grid
* @return {number}
*/
var minimumMoves = function(grid) {
const len = grid.length;
const initPosition = [0, true, 1]
const visited = new Set([initPosition.join()]);
const queue = new Queue();
initPosition.push(0);
queue.enqueue(initPosition)
while (!queue.i... | Minimum Moves to Reach Target with Rotations |
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but ... | class Solution(object):
def merge(self, nums1, m, nums2, n):
# Initialize nums1's index
i = m - 1
# Initialize nums2's index
j = n - 1
# Initialize a variable k to store the last index of the 1st array...
k = m + n - 1
while j >= 0:
if i >= 0 and n... | class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
// Initialize i and j to store indices of the last element of 1st and 2nd array respectively...
int i = m - 1 , j = n - 1;
// Initialize a variable k to store the last index of the 1st array...
int k = m + n... | class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
vector<int> temp(n+m);
int i=0,j=0,k=0;
while(i<m && j<n){ //select smaller element from both vector
if(nums1[i]<nums2[j]){
temp[k]=nums1[i];
i++;
... | var merge = function(nums1, m, nums2, n) {
// Initialize i and j to store indices of the last element of 1st and 2nd array respectively...
let i = m - 1 , j = n - 1;
// Initialize a variable k to store the last index of the 1st array...
let k = m + n - 1;
// Create a loop until either of i or j beco... | Merge Sorted Array |
Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Example 1:
Input: nums = ["01","10"]
Output: "11"
Explanation: "11" does not appear in nums. "00" would... | class Solution(object):
def findDifferentBinaryString(self, nums):
ans='';
for i,num in enumerate(nums):
ans+= '1' if(num[i]=='0') else '0' #ternary if else
#ans+= str(1- int(num[i])); # Alternate: cast to string & 1-x to flip
return ans; | class Solution {
public String findDifferentBinaryString(String[] nums) {
StringBuilder ans= new StringBuilder();
for(int i=0; i<nums.length; i++)
ans.append(nums[i].charAt(i) == '0' ? '1' : '0'); // Using ternary operator
return ans.toString();
... | class Solution {
public:
string findDifferentBinaryString(vector<string>& nums) {
unordered_set<int> s;
for (auto num : nums) s.insert(stoi(num, 0, 2));
int res = 0;
while (++res) {
if (!s.count(res)) return bitset<16>(res).to_string().substr(16-nums.size());
}
... | var findDifferentBinaryString = function(nums) {
return nums.map((s, i) => s[i] == 1 ? '0' : '1').join('');
}; | Find Unique Binary String |
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of ListNode ob... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
root = ListNode(0,head)
summ , d , node = 0 , {} , root
while no... | class Solution {
public ListNode removeZeroSumSublists(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
int prefix = 0;
ListNode curr = dummy;
Map<Integer, ListNode> seen = new HashMap<>();
seen.put(prefix, dummy);
... | class Solution {
public:
ListNode* removeZeroSumSublists(ListNode* head) {
unordered_map<int, ListNode*> m; // {prefix -> node}
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
dummy->next = head;
int prefix = 0;
while(cur){
prefix += cur->val;
... | var removeZeroSumSublists = function(head) {
const dummyHead = new ListNode();
dummyHead.next = head;
let prev = dummyHead;
let start = head;
while (start != null) {
let sum = 0;
let tail = start;
while (tail != null) {
sum += tail.val;
i... | Remove Zero Sum Consecutive Nodes from Linked List |
Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.
Return the resulting string. If there is no way to replace a character to make... | class Solution(object):
def breakPalindrome(self, palindrome):
"""
:type palindrome: str
:rtype: str
"""
s = palindrome
palindrome = [ch for ch in s]
if len(palindrome) == 1:
return ""
for i in range(len(palindrome)//2):
... | class Solution {
public String breakPalindrome(String palindrome) {
int left = 0;
int right = palindrome.length()-1;
if(palindrome.length()==1)
return "";
while(left<right){
char c = palindrome.charAt(left);
... | class Solution {
public:
string breakPalindrome(string palindrome) {
int n = palindrome.size();
string res = "";
if(n==1){
return res;
}
int i = 0;
while(i<n){
if(n%2!=0 && i==n/2){
i++;
continue;
}
... | var breakPalindrome = function(palindrome) {
// domain n / 2 k pehlay
palindrome = palindrome.split('');
const len = palindrome.length;
if(len == 1) return "";
const domain = Math.floor(len / 2);
let firstNonAChar = -1, lastAChar = -1;
for(let i = 0; i < domain; i++) {
if(palindrome[... | Break a Palindrome |
You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:
Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the ... | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
count = Counter(nums)
m = max(nums)
memo = {}
def choose(num):
if num > m:
return 0
if num not in count:
count[num] = 0
if num in memo:
... | class Solution {
public int deleteAndEarn(int[] nums) {
Arrays.sort(nums);
int onePreviousAgo = 0;
int previous = 0;
for(int i = 0; i < nums.length; i++) {
int sum = 0;
// On hop there's no constraint to add the previous value
if(i > 0 && nums[i-1]... | class Solution {
public:
// Dynamic Programming : Bottom Up Approach Optmised
int deleteAndEarn(vector<int>& nums)
{
int size = nums.size();
// Initialise vectors with size 10001 and value 0
vector<int> memo(10001 , 0);
vector<int> res(10001 , 0);
// get the count o... | var deleteAndEarn = function(nums) {
let maxNumber = 0;
const cache = {};
const points = {};
function maxPoints(num) {
if (num === 0) {
return 0;
}
if (num === 1) {
return points[1] || 0;
}
if (cache[num] !== undefin... | Delete and Earn |
Given n orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 1
Output: 1
Explanatio... | class Solution:
def countOrders(self, n: int) -> int:
total = 1
mod = 10 ** 9 + 7
for k in reversed(range(2, n + 1)):
total = total * ((2 * k - 1) * (2 * k - 2) // 2 + 2 * k - 1)
total = total % mod
return total | class Solution {
public int countOrders(int n) {
long res = 1;
long mod = 1000000007;
for (int i = 1; i <= n; i++) {
res = res * (2 * i - 1) * i % mod;
}
return (int)res;
}
} | class Solution {
public:
int countOrders(int n) {
int mod = 1e9+7;
long long ans = 1;
for(int i=1;i<=n;i++){
int m = 2*i-1;
int p = (m*(m+1))/2;
ans=(ans*p)%mod;
}
return ans;
}
}; | var countOrders = function(n) {
let ans = 1; //for n=1, there will only be one valid pickup and delivery
for(let i = 2; i<=n; i++){
let validSlots = 2 * i -1; //calculating number of valid slots of new pickup in (n-1)th order
validSlots = (validSlots * (validSlots+1))/2;
ans = (ans * v... | Count All Valid Pickup and Delivery Options |
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all... | class Solution:
def maxUniqueSplit(self, s: str) -> int:
ans, n = 0, len(s)
def dfs(i, cnt, visited):
nonlocal ans, n
if i == n: ans = max(ans, cnt); return # stop condition
for j in range(i+1, n+1):
if s[i:j] in visited: continue # avoid... | class Solution {
int max = 0;
public int maxUniqueSplit(String s) {
int n = s.length();
backtrack(s, 0, new HashSet<String>());
return max;
}
public void backtrack(String s, int start, Set<String> h) {
if(start == s.length()) {
max = Math.max(max, h.size());
... | class Solution {
public:
unordered_set<string>st;
int ans=0;
void dfs(string &s, int idx)
{
if(st.size()>ans) ans=st.size();
if(idx>=s.length()) return;
string str="";
for(int i=idx ; i<s.length() ; i++)
{
str += s[i];
if(st.find(str)==st.e... | var maxUniqueSplit = function(s) {
let wordSet = new Set(), res = 1;
function checkUniqueSubstring(i) {
if (i === s.length) {
res = Math.max(wordSet.size, res);
return;
}
for (let j = i+1; j <= s.length; j++) {
let str = s.substring(i,j);... | Split a String Into the Max Number of Unique Substrings |
You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tr... | class Solution:
def insertIntoBST(self, root, val):
if not root:
return TreeNode(val)
if val<root.val:
root.left = self.insertIntoBST(root.left, val)
else:
root.right = self.insertIntoBST(root.right, val)
return root | class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
if(root.val > val) root.left = insertIntoBST(root.left, val);
else root.right = insertIntoBST(root.right, val);
return root;
}
} | class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==NULL) return new TreeNode(val);
TreeNode* node = root;
while(true){
if(val>=node->val){
if(node->right) node = node->right;
else{
node->right =... | var insertIntoBST = function(root, val) {
if (root == null) {
return new TreeNode(val);
}
if(val < root.val) {
root.left = insertIntoBST(root.left, val);
} else {
root.right = insertIntoBST(root.right, val);
}
return root;
}; | Insert into a Binary Search Tree |
You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions.
The border of a con... | class Solution:
def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
rows, cols = len(grid), len(grid[0])
border_color = grid[row][col]
border = []
# Check if a node is a border node or not
def is_border(r, c):
if r ==... | class Solution {
public int[][] colorBorder(int[][] grid, int row, int col, int color) {
dfs(grid,row,col,grid[row][col]);
for(int i = 0;i<grid.length;i++)
{
for(int j = 0;j<grid[0].length;j++)
{
if(grid[i][j]<0)
{
grid[i][... | // marking element -ve and then fix it while backtracking worked as visited matrix
// marking element 1e9 and not fixing it while backtracking works for coloring element
class Solution {
private:
int m,n;
public:
bool is_valid(int i,int j,vector<vector<int>> &grid,int org_color){
return i >= 0 and j >= ... | var colorBorder = function(grid, row, col, color) {
const m = grid.length;
const n = grid[0].length;
const dirs = [-1, 0, 1, 0, -1];
const res = [];
for (let i = 0; i < m; i++) {
res[i] = new Array(n).fill(-1);
}
const val = grid[row][col];
const stack = [];
const visited... | Coloring A Border |
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).
Return true if all the rectangles together form an exact cover of a rectangular region.
Example 1:
Input: rectang... | class Solution:
def isRectangleCover(self, rectangles: List[List[int]]) -> bool:
X1, Y1 = float('inf'), float('inf')
X2, Y2 = -float('inf'), -float('inf')
points = set()
actual_area = 0
for x1, y1, x2, y2 in rectangles:
# calculate the coords of the potential per... | class Solution {
// Rectangle x0,y0,x1,y1
public boolean isRectangleCover(int[][] rectangles) {
// Ordered by y0 first and x0 second
Arrays.sort(rectangles,(r1,r2)->{
if(r1[1]==r2[1]) return r1[0]-r2[0];
return r1[1]-r2[1];
});
// Layering rectangles with ... | class Solution {
public:
bool isRectangleCover(vector<vector<int>>& rectangles) {
SegmentTree<STMax> st(2e5 + 1);
sort(rectangles.begin(), rectangles.end(), [](auto& lhs, auto& rhs) -> bool {
if (lhs[1] != rhs[1]) return lhs[1] < rhs[1];
return lhs[0] < rhs[0];
});
int min_x = rectangles... | var isRectangleCover = function(R) {
// left to right, bottom to top (so sort on bottom first, then left)
R.sort(([left1, bottom1], [left2, bottom2]) => bottom1 - bottom2 || left1 - left2);
// Find all corners
let leftMost = Infinity,
bottomMost = Infinity,
rightMost = -Infinity,
... | Perfect Rectangle |
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Outpu... | class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
# if target is not in nums list, we simply return [-1,-1]
if target not in nums:
return [-1,-1]
# create an empty list
result = []
# iterate nums for the first time, if we found nums[i] match... | class Solution {
public int[] searchRange(int[] nums, int target) {
int[] ans={-1,-1};
int start=search(nums,target,true);
int end=search(nums,target,false);
ans[0]=start;
ans[1]=end;
return ans;
}
int search(int[] nums ,int target,boolean findStart){
... | class Solution {
public:
int startEle(vector<int>& nums, int target,int l,int r)
{
while(l<=r)
{
int m = (l+r)/2;
if(nums[m]<target) l=m+1;
else if(nums[m]>target) r = m-1;
else
{
if(m==0)
return m;
... | var searchRange = function(nums, target) {
if (nums.length === 1) return nums[0] === target ? [0, 0] : [-1, -1];
const findFirstInstance = (left, right) => {
if (left === right) return left;
var pivot;
while (left < right) {
if (left === pivot) left += 1;
piv... | Find First and Last Position of Element in Sorted Array |
Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.
A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.
Recall that a permut... | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
d={}
for i,v in enumerate(pattern):
if v in d:
d[v].append(i)
else:
d|={v:[i]}
#DICTIONARY CONTAINING LETTERS AND THEIR INDICES
ans=[]... | class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> result=new ArrayList<>();
for(String word:words) {
Map<Character,Character> map=new HashMap<>();
Set<Character> set=new HashSet<>();
int i=0;
for(... | //😉If you Like the repository don't foget to star & fork the repository😉
class Solution {
public:
vector<int> found_Pattern(string pattern)
{
// if string is empty return empty vector.
if(pattern.size() == 0)
return {};
vector<int> v;
// ind variable for k... | var findAndReplacePattern = function(words, pattern) {
var patt = patternarr(pattern) // 010
return words.filter(e=>patternarr(e) == patt)
};
const patternarr = function (str) {
var result = '';
for(let i=0;i<str.length;i++) {
//finding the first index
result += str.indexOf(str[i])
... | Find and Replace Pattern |
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.
Example 2:
Input: s = "aba"
Output: false
Example 3:
Input: s = "abcabcabcabc"
Outpu... | class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
for i in range(1, len(s)//2+1):
if s[:i] * (len(s)//i) == s:
return True
return False | class Solution {
public boolean repeatedSubstringPattern(String s) {
String temp="";
for(int i=0 ;i<s.length()/2 ;i++){
temp+=s.charAt(i);
if(s.length()%temp.length()==0) {
int times_repeat= s.length()/temp.length();
StringBuilder str = new Stri... | class Solution {
public:
vector<int> get_kmp_table(const string &s) {
vector<int> table(s.size());
int i=0; int j=-1;
table[0] = -1;
while (i < s.size()) {
if (j == -1 || s[i] == s[j]) {
i++;
j++;
table[i] = j;
... | var repeatedSubstringPattern = function(s) {
let repeatStr = s.repeat(2) //first duplicate the string with repeat function
let sliceStr = repeatStr.slice(1,-1) // slice string first and last string word
return sliceStr.includes(s) // now check if the main string(s) is included by sliced string
} | Repeated Substring Pattern |
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped m... | import numpy
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
return numpy.reshape(mat,(r,c)) if r*c==len(mat)*len(mat[0]) else mat | class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
if (r * c != mat.length * mat[0].length) {
return mat;
}
int[][] ans = new int[r][c];
int i = 0;
int j = 0;
for(int k = 0; k < mat.length; k++) {
for(int l = 0; l < ... | class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
if(mat.size()* mat[0].size()!= r * c) {
return mat;
}
vector<vector<int>>v(r,vector<int>(c));
int k = 0;
int l = 0;
for(int i = 0; i < mat.size(); i++) {... | var matrixReshape = function(mat, r, c) {
const origR = mat.length;
const origC = mat[0].length;
if (r*c !== origR*origC) {
return mat;
}
const flat = mat.flatMap(n => n);
const output = [];
for (let i=0; i<flat.length; i++) {
if (i%c === 0) {
output.push([]);
}
output[... | Reshape the Matrix |
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
... | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
def number(head):
ans = ''
while head:
ans+=str(head.val)
head = head.next
return int(ans)
temp = dummy = ListNode(0)
... | class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res=new ListNode(0);
ListNode curr=res;
l1=reverseLinkedList(l1);
l2=reverseLinkedList(l2);
int carry=0;
while(l1!=null||l2!=null||carry==1)
{
int sum=0;
... | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverse(Lis... | var addTwoNumbers = function(l1, l2) {
const reverse = head =>{
let prev = null
let dummy = head
while(dummy){
let temp = dummy.next
dummy.next = prev
prev = dummy
dummy = temp
}
return prev
}
let head1 = reverse(l1)
... | Add Two Numbers II |
An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixe... | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
queue = deque()
rows = len(image)
cols = len(image[0])
targetColor = image[sr][sc]
if color == targetColor:
# in this case, we don't need to d... | class Solution {
void colorFill(int[][]image,int sr,int sc,int sourceColor,int targetColor){
int m = image.length, n = image[0].length;
if(sr>=0 && sr<m && sc>=0 && sc<n)
{
if( (image[sr][sc] != sourceColor) ||(image[sr][sc] == targetColor)) return;
image[sr][sc] = targ... | class Solution {
public:
vector<vector<int>> paths = {{0,1},{0,-1},{-1,0},{1,0}};
bool check(int i,int j , int n, int m){
if(i>=n or i<0 or j>=m or j<0) return false;
return true;
}
void solve(vector<vector<int>> &image, int sr, int sc, int color, int orig){
int n = image.size(),... | /**
* @param {number[][]} image
* @param {number} sr
* @param {number} sc
* @param {number} color
* @return {number[][]}
*/
var floodFill = function(image, sr, sc, color) {
const pixelsToCheck = [[sr, sc]]
const startingPixelColor = image[sr][sc]
const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
... | Flood Fill |
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-... | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
hrow = {}
hcol = {}
hbox = defaultdict(list)
#CHECK FOR DUPLICATES ROWWISE
for i in range(9):
for j in range(9):
#JUST THAT THE DUPLICATE SHOULDNT BE ","
if... | for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
if(board[i][j] != '.'){
char currentVal = board[i][j];
if(!(seen.add(currentVal + "found in row "+ i)) ||
!(seen.add(currentVal + "found in column "+ j) ) ||
!(seen.add(currentVal + "... | class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int n = board.size();
for(int i=0;i<n;i++){
unordered_map<char,int>m;
for(int j=0;j<board[i].size();j++){
if(board[i][j]=='.'){
continue;
... | /**
* @param {character[][]} board
* @return {boolean}
*/
var isValidSudoku = function(board) {
let rowMap = new Map();
let colMap = new Map();
let square = new Map();
for(let i=0; i<board.length; i++) {
for(let j=0; j<board[0].length; j++) {
if(board[i][j] === '.') continue;
... | Valid Sudoku |
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = ... | class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)-1
while left<=right:
mid = (left+right)//2
if nums[mid]==target:
return mid
elif nums[mid]>target:
right = mid-1
... | class Solution {
public int search(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
return binarySearch(nums, l, r, target);
}
private int binarySearch(int[] nums, int l, int r, int target) {
if (l <= r) {
int mid = (r + l) / 2;
... | class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
int jump = 5;
int p = 0;
while (jump*5 < n) jump *= 5;
while (jump > 0) {
while (p+jump < n && nums[p+jump] <= target) p += jump;
jump /= 5;
}
ret... | /**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let low=0;
let high=nums.length-1;
if(target<nums[0] || target>nums[high]){
return -1;
}
while(low<=high) {
mid=Math.floor((low+high)/2);
... | Binary Search |
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".
One of the benefits of the ... | class MyCircularQueue {
int head = -1;
int tail = -1;
int[] q;
int k;
public MyCircularQueue(int k) {
q = new int[k];
this.k = k;
}
public boolean enQueue(int value) {
if(head == -1 && tail == -1) {
// enqueue when the queue is empty
... | class MyCircularQueue {
private int front;
private int rear;
private int[] arr;
private int cap;
private int next(int i){ // to get next idx after i in circular queue
return (i+1)%cap;
}
private int prev(int i){ // to get prev idx before i in circular queue
return (i+ca... | class MyCircularQueue {
int head = -1;
int tail = -1;
int[] q;
int k;
public MyCircularQueue(int k) {
q = new int[k];
this.k = k;
}
public boolean enQueue(int value) {
if(head == -1 && tail == -1) {
// enqueue when the queue is empty
... | class MyCircularQueue {
int head = -1;
int tail = -1;
int[] q;
int k;
public MyCircularQueue(int k) {
q = new int[k];
this.k = k;
}
public boolean enQueue(int value) {
if(head == -1 && tail == -1) {
// enqueue when the queue is empty
... | Design Circular Queue |
Design a data structure that efficiently finds the majority element of a given subarray.
The majority element of a subarray is an element that occurs threshold times or more in the subarray.
Implementing the MajorityChecker class:
MajorityChecker(int[] arr) Initializes the instance of the class with the given arra... | MAX_N = 2*10**4
MAX_BIT = MAX_N.bit_length()
class MajorityChecker:
def __init__(self, nums: List[int]):
n = len(nums)
self.bit_sum = [[0] * MAX_BIT for _ in range(n+1)]
for i in range(1, n+1):
for b in range(MAX_BIT):
self.bit_sum[i][b] = self.bit_sum[i-1][b] + ... | class MajorityChecker {
private final int digits=15;
private int[][]presum;
private ArrayList<Integer>[]pos;
public MajorityChecker(int[] arr) {
int len=arr.length;
presum=new int[len+1][digits];
pos=new ArrayList[20001];
for(int i=0;i<len;i++){
... | class MajorityChecker {
public:
MajorityChecker(vector<int>& arr) {
this->arr = arr;
map<int, int> cnt;
for (auto& v: arr) {
cnt[v]++;
}
val_idx = vector<int>(20001, -1);
for (auto it = cnt.begin(); it != cnt.end(); ++it) {
if (it->second >= 25... | var MajorityChecker = function(arr) {
this.arr = arr;
};
MajorityChecker.prototype.query = function(left, right, threshold) {
var candidate = 0
var count = 0
for (var i = left; i < right+1; i++) {
if (count == 0) {
candidate = this.arr[i];
count = 1;
}
el... | Online Majority Element In Subarray |
You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.
To complete the ith replacement operation:
Check if the substring sources[i] occurs at index indices[i] in th... | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
inputs = list(zip(indices,sources,targets))
inputs.sort(key = lambda x: x[0])
offset = 0
for idx, src, tgt in inputs:
idx += offset
... | class Solution {
public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
HashMap<Integer, String> subst = new HashMap<>();
HashMap<Integer, String> tgt = new HashMap<>();
for(int i = 0; i< indices.length; i++) {
subst.put(i... | class Solution {
public:
string findReplaceString(string s, vector<int>& indices, vector<string>& sources, vector<string>& targets) {
int baggage = 0;
int n = indices.size();
map<int, pair<string,string>> mp;
for(int i=0;i<n;++i)
{
mp[indices[i]]={sources[i],... | var findReplaceString = function(s, indices, sources, targets) {
let res = s.split('');
for(let i=0; i<indices.length; i++) {
let index = indices[i];
let str = sources[i];
if(s.slice(index, index + str.length) == str) {
res[index] = targets[i];
for(... | Find And Replace in String |
Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists.
A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading ze... | class Solution:
def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:
ogLength = intLength
isOdd = intLength & 1
if isOdd:
intLength += 1
k = intLength // 2
k = 10 ** (k - 1)
op = []
for q in queries:
pal = str(k + q... | class Solution {
public long[] kthPalindrome(int[] queries, int intLength) {
long[] res= new long[queries.length];
for(int i=0;i<queries.length;i++){
res[i]=nthPalindrome(queries[i],intLength);
}
return res;
}
public long nthPalindrome(int nth, int kdigit)
{
... | #define ll long long
class Solution {
public:
vector<long long> kthPalindrome(vector<int>& queries, int intLength) {
vector<ll> result;
ll start = intLength % 2 == 0 ? pow(10, intLength/2 - 1) : pow(10, intLength/2);
for(int q: queries) {
string s = to_string(start + q - 1);
... | var kthPalindrome = function(queries, intLength) {
let output=[];
// 1. We use FIRST 2 digits to create palindromes: Math.floor((3+1)/2)=2
let digit=Math.floor((intLength+1)/2);
for(let i=0; i<queries.length; i++){
// 2A. Get Nth 2-digits numbers: 10*(2-1)-1+[5,98]=[14,107]
let helper=1... | Find Palindrome With Fixed Length |
You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum.
Return any such subsequence as an integer array of length k.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of... | class Solution(object):
def maxSubsequence(self, nums, k):
ret, max_k = [], sorted(nums, reverse=True)[:k]
for num in nums:
if num in max_k:
ret.append(num)
max_k.remove(num)
if len(max_k) == 0:
return ret | class Solution {
public int[] maxSubsequence(int[] nums, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> b[0] - a[0]);
for(int i=0; i<nums.length; i++)
pq.offer(new int[]{nums[i], i});
List<int[]> l = new ArrayList<>();
while(k--... | // OJ: https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
vector<int> maxSubsequence(vector<int>& A, int k) {
vector<int> id(A.size());
iota(begin(id), end(id), 0); // Index array... | var maxSubsequence = function(nums, k) {
return nums.map((v,i)=>[v,i]).sort((a,b)=>a[0]-b[0]).slice(-k).sort((a,b)=>a[1]-b[1]).map(x=>x[0]);
}; | Find Subsequence of Length K With the Largest Sum |
You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.
In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the... | from bisect import bisect_left
class Solution:
def minOperations(self, target: List[int], arr: List[int]) -> int:
dt = {num: i for i, num in enumerate(target)}
stack = []
for num in arr:
if num not in dt: continue
i = bisect_left(stack, dt[num])
if i == le... | class Solution {
public int minOperations(int[] target, int[] arr) {
int n = target.length;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < n; i++) {
map.put(target[i], i);
}
List<Integer> array = new ArrayList<>();
for(int i = 0; i < ar... | class Solution {
public:
vector<int> ans;
void bin(int lo, int hi, int num) {
if(lo == hi) {
ans[lo] = num;
return;
}
int mid = (lo + hi) / 2;
if(ans[mid] < num) bin(mid + 1, hi, num);
else bin(lo, mid, num);
}
int minOperations(v... | const minOperations = function (targets, arr) {
const map = {};
const n = targets.length;
const m = arr.length;
targets.forEach((target, i) => (map[target] = i));
//map elements in arr to index found in targets array
const arrIs = arr.map(el => {
if (el in map) {
return map[el];
} else {
... | Minimum Operations to Make a Subsequence |
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return true if n is an ugly number.
Example 1:
Input: n = 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore all of its prime facto... | class Solution:
def isUgly(self, n: int) -> bool:
if n == 0:
return False
res=[2, 3, 5]
while n!= 1:
for i in res:
if n%i==0:
n=n//i
break
else:
return False
return True | class Solution {
public boolean isUgly(int n) {
if(n==0) return false; //edge case
while(n!=1){
if(n%2==0){
n=n/2;
}
else if(n%3==0){
n=n/3;
}
else if(n%5==0){
n=n/5;
}
el... | class Solution {
public:
bool isUgly(int n)
{
if (n <= 0) return false;
int n1 = 0;
while(n != n1)
{
n1 = n;
if ((n % 2) == 0) n /= 2;
if ((n % 3) == 0) n /= 3;
if ((n % 5) == 0) n /= 5;
}
if (n < 7) return true;
return false;
}
}; | var isUgly = function(n) {
let condition = true;
if(n == 0) // 0 has infinite factors. So checking if the number is 0 or not
return false;
while(condition){ //applying for true until 2, 3, 5 gets removed from the number
if(n % 2 == 0)
n = n / 2;
else if(n % 3 == 0)
... | Ugly Number |
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog ... | class Solution(object):
def wordPattern(self, pattern, s):
"""
:type pattern: str
:type s: str
:rtype: bool
"""
p, s = list(pattern), list(s.split(" "))
return len(s) == len(p) and len(set(zip(p, s))) == len(set(s)) == len(set(p)) | class Solution {
public boolean wordPattern(String pattern, String s) {
String[] arr=s.split(" ");
if(pattern.length()!=arr.length) return false;
Map<Character,String> map=new HashMap<Character,String>();
for(int i=0;i<pattern.length();i++){
char ch=pattern.char... | class Solution {
public:
unordered_set<string> processed_words;
string m[26]; // char to string mapping
bool crunch_next_word(char c, string word)
{
int idx = c-'a';
if(m[idx].empty() && processed_words.count(word)==0)
{
m[idx] = word;
processed_words.in... | var wordPattern = function(pattern, s) {
let wordArray = s.split(" ");
if(wordArray.length !== pattern.length) return false;
let hm = {};
let hs = new Set();
for(let index in pattern) {
let word = wordArray[index];
let char = pattern[index];
if(hm[char] !== undefined) {
... | Word Pattern |
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into o... | class Solution:
def rob(self, nums: List[int]) -> int:
# [rob1,rob2,n,n+1]
# 1 | 2 | 3 | 1
#index 0 1 2 3
# so upto last index it depends on previous 2 values :
# here upto 2nd index max rob is 1+3=4; not choosing adjacent element 2
# and upto 1st index max rob is 2 ; not... | class Solution {
public int rob(int[] nums) {
int[] t = new int[nums.length] ;
for(int i=0; i<t.length; i++){
t[i] =-1;
}
return helper(nums,0,t);
}
static int helper(int[] nums, int i,int[] t){
if(i>=nums.length){
return 0;
}
if... | class Solution {
public:
int helper(int i, vector<int>& nums) {
if(i == 0) return nums[i];
if(i < 0) return 0;
int pick = nums[i] + helper(i-2, nums);
int not_pick = 0 + helper(i-1, nums);
return max(pick,not_pick);
}
int rob(vector<int>& nums) {
return help... | const max=(x,y)=>x>y?x:y
var rob = function(nums) {
if(nums.length==1) return(nums[0]);
let temp=[]
temp[0]=nums[0];
temp[1]=max(nums[0],nums[1]);
for(let i =2;i<nums.length;i++){
temp[i] = max(temp[i-1],nums[i]+temp[i-2]);
}
// console.log(temp)
return(... | House Robber |
Convert a non-negative integer num to its English words representation.
Example 1:
Input: num = 123
Output: "One Hundred Twenty Three"
Example 2:
Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Fiv... | class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return "Zero"
dic1 = {1000000000: "Billion", 1000000: "Million", 1000: "Thousand", 1: ""}
dic2 = {90: "Ninety", 80: "Eighty", 70: "Seventy", 60: "Sixty", 50: "Fifty", 40: "Forty", 30: "Thirty... | class Solution {
private static final int[] INT_NUMBERS = {
1_000_000_000, 1_000_000, 1000, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
private static final String[] STRING_NUMBERS = {
"Billion", "Million", "Thousand", "Hu... | unordered_map<int, string> mp_0 = {{1, "One "},{2, "Two "},{3, "Three "},{4, "Four "}, {5, "Five "},{6, "Six "},{7, "Seven "},{8, "Eight "},{9, "Nine "}, {10, "Ten "},{11,"Eleven "},{12, "Twelve "},{13, "Thirteen "},{14, "Fourteen "},{15, "Fifteen "},{16, "Sixteen "},{17, "Seventeen "},{18, "Eighteen "},{19, "Nineteen... | let numberMap = {
0: 'Zero',
100: 'Hundred',
1: 'One',
2: 'Two',
3: 'Three',
4: 'Four',
5: 'Five',
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine',
10: 'Ten',
11: 'Eleven',
12: 'Twelve',
13: 'Thirteen',
14: 'Fourteen',
15: 'Fifteen',
16: 'Sixteen',
17: 'Seventeen',
18: 'Eighteen',
1... | Integer to English Words |
Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.
He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday.
Given n, retu... | from itertools import cycle, \
repeat, \
starmap
from operator import floordiv
class Solution:
def totalMoney(self, n: int) -> int:
return sum(starmap(add,zip(
starmap(floordiv, zip(range(n), repeat(7, n))),
cycle((1,2,3,4,5,6,7))
... | class Solution {
public int totalMoney(int n) {
int m=n/7; //(no.of full weeks)
// first week 1 2 3 4 5 6 7 (sum is 28 i.e. 7*(i+3) if i=1)
// second week 2 3 4 5 6 7 8 (sum is 35 i.e. 7*(i+3) if i=2)
//.... so on
int res=0; //for result
//calculating full weeks
... | class Solution {
public:
int totalMoney(int n) {
int res = 0;
for (int i = 1, c = 1; i <= n; i++, c++) {
res += c;
c = i % 7 ? c : (i / 7);
}
return res;
}
}; | var totalMoney = function(n) {
let min = 1;
let days = 7;
let total = 0;
let inc = 1;
for (let i = 0; i < n; i++) {
if (days !== 0) {
total += min;
min++;
days--;
} else {
inc++;
min = inc
days = 7;
i... | Calculate Money in Leetcode Bank |
You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.
If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as... | from functools import cache
class Solution:
def maxCoins(self, nums: List[int]) -> int:
nums = [1] + nums + [1]
length = len(nums)
dp = [[None]*(length+1) for i in range(length+1)]
@cache
def dfs(l,r):
if l>r: return 0
if dp[l][r] is not None... | class Solution {
public int maxCoins(int[] nums) {
int n = nums.length;
// adding 1 to the front and back
int[] temp = new int[n + 2];
temp[0] = 1;
for(int i = 1; i < temp.length - 1; i++){
temp[i] = nums[i-1];
}
temp[temp.length - 1] = ... | class Solution {
public:
//topDown+memoization
int solve(int i,int j,vector<int>& nums,vector<vector<int>>& dp){
if(i>j) return 0;
if(dp[i][j]!=-1) return dp[i][j];
int maxcost = INT_MIN;
for(int k = i;k<=j;k++){
int cost = nums[i-1]*nums[k]*nums[j+1]+solve(i... | var rec = function(i,j,arr,dp){
if(i>j)return 0;
if(dp[i][j] !== -1)return dp[i][j];
let max = Number.MIN_VALUE;
for(let k=i;k<=j;k++){
let cost = arr[i-1] * arr[k] * arr[j+1] + rec(i,k-1,arr,dp)+rec(k+1,j,arr,dp);
if(cost>max){
max = cost
}
}
return dp[i][j] ... | Burst Balloons |
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
Example 1:
Input: nums = [11,7,2,15]
Output: 2
Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.
Element 1... | class Solution:
def countElements(self, nums: List[int]) -> int:
M = max(nums)
m = min(nums)
return sum(1 for i in nums if m<i<M) | class Solution {
public int countElements(int[] nums) {
int nmin=Integer.MAX_VALUE;
int nmax=Integer.MIN_VALUE;
for(int a:nums)
{
nmin=Math.min(a,nmin);
nmax=Math.max(a,nmax);
}
int count=0;
for(int a:nums)
{
if(a>nm... | class Solution {
public:
int countElements(vector<int>& nums) {
int M = *max_element(nums.begin(), nums.end());
int m = *min_element(nums.begin(), nums.end());
int res = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i] > m && nums[i] < M) res++;
}
ret... | var countElements = function(nums) {
let map = {}, total = 0;
// adding elements to map
for(let i of nums) map[i] ? map[i]++ : map[i] = 1;
// Removing repeated elements
let newNums = [... new Set(nums)];
// If length of array after removing repeated nums is less than three return 0;
if(ne... | Count Elements With Strictly Smaller and Greater Elements |
In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represe... | class UnionFind:
def __init__(self, size):
self.parent = [-1 for _ in range(size)]
self.rank = [-1 for _ in range(size)]
def find(self, i):
if self.parent[i] == -1:
return i
k = self.find(self.parent[i])
self.parent[i] ... | class Solution {
public int[] findRedundantConnection(int[][] edges) {
UnionFind uf = new UnionFind(edges.length);
for (int[] edge : edges) {
if (!uf.union(edge[0], edge[1])) {
return new int[]{edge[0], edge[1]};
}
}
return null;
}
pri... | class UnionFind {
public:
int* parent;
int* rank;
UnionFind(int n){
rank = new int[n];
parent = new int[n];
for(int i=0; i<n; i++){
parent[i] = i;
rank[i] = 0;
}
}
// collapsing find
int Find(int node){
// if parent of node ... | var findRedundantConnection = function(edges) {
const root = [];
const find = (index) => {
const next = root[index];
return next ? find(next) : index;
};
for (const [a, b] of edges) {
const x = find(a);
const y = find(b);
if (x === y) return [a, b];
root... | Redundant Connection |
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess ... | class Solution:
def knightDialer(self, n: int) -> int:
# Sum elements of matrix modulo mod subroutine
def sum_mat(matrix, mod):
return sum(sum(row) % mod for row in matrix) % mod
# Matrix multiplication subroutine
def mult_mat(a, b):
return [[sum(a[i]... | class Solution {
public int knightDialer(int n) {
var dp = new long[10];
var tmp = new long[10];
Arrays.fill(dp, 1);
for (int i = 1; i < n; i++) {
tmp[1] = dp[6]+dp[8];
tmp[2] = dp[7]+dp[9];
tmp[3] = dp[4]+dp[8];
tmp[4] = dp[0]+dp[3]+dp... | class Solution {
int MOD=1e9+7;
public:
int knightDialer(int n) {
if(n==1) return 10;
int a=2, b=2, c=3, d=2; //a{2,8} b{1,3,7,9} c{4,6} d{0}
for(int i=3; i<=n; i++){
int w, x, y, z;
w = 2ll*b%MOD;
x = (1ll*a + 1ll*c)%MOD;
y = (2ll*b + 1ll*... | var knightDialer = function(n) {
let dp = Array(10).fill(1)
let MOD = 10**9 + 7
for(let i = 2; i <= n ; i++) {
oldDp = [...dp]
dp[0] = (oldDp[4] + oldDp[6]) % MOD
dp[1] = (oldDp[8] + oldDp[6]) % MOD
dp[2] = (oldDp[9] + oldDp[7]) % MOD
dp[3] = (oldDp[8] + oldDp[4]) %... | Knight Dialer |
Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
Example 1:
Input: s = "eleetminicoworoep"
Output: 13
Explanation: The longest substring is "leetminicowor" which contains two eac... | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
integrals = [(False, False, False, False, False)] # integrals[10][mapping["a"]] == False means we have seen "a" appears even times before index 10
mapping = {
"a": 0,
"i": 1,
"u": 2,
"e"... | class Solution {
public int findTheLongestSubstring(String s) {
int res = 0 , mask = 0, n = s.length();
HashMap<Integer, Integer> seen = new HashMap<>();// key--> Mask, value--> Index
seen.put(0, -1);
for (int i = 0; i < n; ++i) {
if(s.charAt(i)=='a' || s.charAt(i)=='e' ... | //When the xor of all the even times numbers are done it results in 0. The xor of the vowels are done by indicating
//them with a single digit and the xor value is stored in a map
class Solution {
public:
int findTheLongestSubstring(string s) {
int x= 0;
unordered_map<int,int>mp;
mp[0]=-1;
... | var findTheLongestSubstring = function(s) {
// u o i e a
// 0 0 0 0 0 => initial state, all are even letters
// s = "abcab"
// 0 0 0 0 1 => at index 0, only a is odd count
// 0 0 0 0 1 => at index 1, max = 1
// 0 0 0 0 1 => at index 2, max = 2
// 0 0 0 0 0 => at index 3, max = 4
// 0 0 0... | Find the Longest Substring Containing Vowels in Even Counts |
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, en... | class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
mix, res, last_i = DefaultDict(int), [], 0
for start, end, color in segments:
mix[start] += color
mix[end] -= color
for i in sorted(mix.keys()):
if last_i in mix and mix... | class Solution {
//class for segments
class Seg{
int val,end;
int color;
boolean isStart;
public Seg(int val,int end,int color, boolean isStart){
this.val = val;
this.end = end;
this.color = color;
this.isStart = isStart;
... | typedef long long ll;
class Solution {
public:
vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {
vector<vector<ll> > ans;
map<int,ll> um;
for(auto s : segments){
um[s[0]] += s[2];
um[s[1]] -= s[2];
}
bool flag = false;
... | /**
* @param {number[][]} segments
* @return {number[][]}
*/
var splitPainting = function(segments) {
const arr = [];
segments.forEach(([start, end, val])=>{
arr.push([start, val]);
arr.push([end, -val]);
});
arr.sort((i,j)=>i[0]-j[0]);
const ans = [];
let currVal = 0, prevTi... | Describe the Painting |
The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same.
Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.
... | class Solution:
class Solution:
def largestVariance(self, s: str) -> int:
def maxSubArray(nums: List[int]):
ans=-float('inf')
runningSum=0
seen=False
for x in (nums):
if x<0:
seen=True
runningSum... | class Solution {
public int largestVariance(String s) {
int [] freq = new int[26];
for(int i = 0 ; i < s.length() ; i++)
freq[(int)(s.charAt(i) - 'a')]++;
int maxVariance = 0;
for(int a = 0 ; a < 26 ; a++){
for(int b = 0 ; b < 26 ; b++){
... | /*
Time: O(26*26*n)
Space: O(1)
Tag: Kadane's Algorithm
Difficulty: H (Logic) | E(Implementation)
*/
class Solution {
public:
int largestVariance(string s) {
int res = 0;
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
if (i == j) continue;
... | var largestVariance = function(s) {
let chars = new Set(s.split("")), maxDiff = 0;
for (let l of chars) {
for (let r of chars) {
if (l === r) continue;
let lCount = 0, rCount = 0, hasRight = false;
for (let char of s) {
lCount += char === l ? 1 : 0;
rCount += char === r ? 1 : 0... | Substring With Largest Variance |
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.
The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).
The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner... | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
def segment(ax1,ax2,bx1,bx2):
return min(ax2,bx2) - max(ax1, bx1) if max(ax1, bx1) < min(ax2, bx2) else 0
return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - segme... | class Solution {
public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
int x1 = Math.max(ax1,bx1);
int y1 = Math.max(ay1,by1);
int x2 = Math.min(ax2,bx2);
int y2 = Math.min(ay2,by2);
int area = 0;
int R1 = (ax2-ax1)*(ay2-ay1... | class Solution {
public:
int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
int rec1=abs(ax2-ax1)*abs(ay2-ay1); //Area(Rectangle 1)
int rec2=abs(bx2-bx1)*abs(by2-by1); //Area(Rectangle 2)
//As explained above, if intervals overlap, max(x1,x3) < min(x2,... | var computeArea = function(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) {
let area1 = (ax2-ax1)*(ay2-ay1)
let area2 = (bx2-bx1)*(by2-by1)
let overlap = (by1>ay2 || by2<ay1 || bx1>ax2 || bx2<ax1) ? 0 : Math.abs((Math.min(ax2,bx2) - Math.max(ax1, bx1))*(Math.min(ay2,by2) - Math.max(ay1, by1)))
return area... | Rectangle Area |
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers.
For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum ... | class Solution:
def maximumEvenSplit(self, finalSum: int) -> List[int]:
l=[]
if finalSum%2!=0:
return l
else:
s=0
i=2 # even pointer 2, 4, 6, 8, 10, 12...........
while(s<finalSum):
s+=i #sum
l.append(i) # append... | class Solution {
public List<Long> maximumEvenSplit(long finalSum) {
List<Long> res = new ArrayList<Long>();
//odd sum cannot be divided into even numbers
if(finalSum % 2 != 0) {
return res;
}
//Greedy approach, try to build the total sum using minimum unique even... | class Solution {
public:
using ll = long long;
ll bs(ll low , ll high, ll fs){
ll ans = 1;
while(low<=high){
ll mid = low + (high-low)/2;
if(mid*(mid+1)>fs){
high = mid-1; // If sum till index equal to 'mid' > fs then make high = mid-1
}
... | var maximumEvenSplit = function(finalSum) {
if(finalSum % 2) return [];
const set = new Set();
let n = 2, sum = 0;
while(sum < finalSum) {
sum += n;
set.add(n);
n += 2;
}
set.delete(sum - finalSum);
return [...set];
}; | Maximum Split of Positive Even Integers |
Given an array of integers nums, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Constraints:
1 <= nums.length <= 5 * 104
-5 * 104 <= nums[i] <= 5 * 104
| import heapq
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
h = {}
for i in nums:
if i in h:
h[i]+=1
else:
h[i]=1
heap = []
for i in h:
heap.append([i,h[i]])
hea... | class Solution {
public void downHeapify(int[] nums, int startIndex, int lastIndex){
int parentIndex = startIndex;
int leftChildIndex = 2*parentIndex + 1;
int rightChildIndex = 2*parentIndex + 2;
while(leftChildIndex <= lastIndex){
int maxIndex = parentIndex;
... | class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
priority_queue<int, vector<int>, greater<int>>pq;
for(auto it : nums)
{
pq.push(it);
}
vector<int>ans;
while(!pq.empty())
{
ans.push_back(pq.top());
pq.pop(... | var sortArray = function(nums) {
return quickSort(nums, 0, nums.length - 1);
};
const quickSort = (arr, start, end) => {
// base case
if (start >= end) return arr;
// return pivot index to divide array into 2 sub-arrays.
const pivotIdx = partition(arr, start, end);
// sort sub-array to the lef... | Sort an Array |
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
Example 1:
Input: cost = [1... | class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
n = len(cost)
dp = cost[:2] + [0]*(n-2)
for i in range(2, n):
dp[i] = min(dp[i-1], dp[i-2]) + cost[i]
return min(dp[-1], dp[-2]) | class Solution {
public int minCostClimbingStairs(int[] cost) {
int a[] = new int[cost.length+1];
a[0]=0;
a[1]=0;
for(int i=2;i<=cost.length;i++)
{
a[i]= Math.min(cost[i-1]+a[i-1], cost[i-2]+a[i-2]);
}
return a[cost.length];
}
} | class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
/* Minimize cost of steps, where you can take one or two steps.
At each step, store the minimum of the current step plus the step previous
or the step two previous. At the last step we can either take t... | var minCostClimbingStairs = function(cost) {
//this array will be populated with the minimum cost of each step starting from the top
let minCostArray = [];
//append a 0 at end to represent reaching the 'top'
minCostArray[cost.length] = 0;
//append the last stair to the end of the array
minCostAr... | Min Cost Climbing Stairs |
Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following ... | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
Alice , Bob = capacityA, capacityB
res, i, j = 0, 0, len(plants)-1
while i < j:
if Alice >= plants[i]:
Alice -= plants[i]
els... | class Solution {
public int minimumRefill(int[] plants, int capacityA, int capacityB) {
int count=0;
int c1=capacityA,c2=capacityB;
for(int start=0,end=plants.length-1;start<=plants.length/2&&end>=plants.length/2;start++,end--){
if(start==end||start>end)break;
if(c1>=... | class Solution {
public:
int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {
int n(plants.size()), res(0), aliceC(capacityA), bobC(capacityB), alice(0), bob(n-1);
while (alice < bob)
{
if (alice == bob)
{
if (aliceC < ... | var minimumRefill = function(plants, capacityA, capacityB) {
const n = plants.length;
let left = 0;
let right = n - 1;
let remA = capacityA;
let remB = capacityB;
let refills = 0;
while (left < right) {
const leftAmount = plants[left++];
const rightAmount = plants[right--... | Watering Plants II |
Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.
Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not con... | class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
A = digits
A.sort()
A.reverse()
@cache
def DP(i, r): # max number whose remainder is r using subarray [0:i] (inclusive)
if i == 0:
if A[0] % 3 == r:
return A[0]
else:
return 0
Ra = DP(i-1, r)
Rb = [ x fo... | class Solution {
public String largestMultipleOfThree(int[] digits) {
int n=digits.length;
Arrays.sort(digits);
if(digits[digits.length-1]==0){
return "0";
}
int sum=0;
for(int i=0;i<digits.length;i++){
sum+=digits[i]... | class Solution {
public:
vector<int> ans;
void calculate(vector<int>& count,int no,vector<int>& temp){
if(no==0){
int flag=0,sum1=0,sum2=0,validSum=0;
for(int j=1;j<10;j++){
sum1+=temp[j];
sum2+=ans[j];
validSum+=(temp[j]*j);
... | /**
* @param {number[]} digits
* @return {string}
*/
var largestMultipleOfThree = function(digits) {
// highest digit first
digits.sort((l, r) => r - l);
// what is the remainder of the total sum?
const sumRemainder = digits.reduce((a, c) => a + c, 0) % 3;
if (sumRemainder) {
le... | Largest Multiple of Three |
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.
Example 1:
Input: nums = [8,2,4,7], limit = 4
Output: 2
Explanation: All subarrays are:
[8] with ... | # max absolte diff within a subarray is subarray max substracted by subarray min
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
q = collections.deque() # monotonic decreasing deque to compute subarray max, index of
q2 = collections.deque() # monotonic increasing deque... | class Solution {
public int longestSubarray(int[] nums, int limit) {
Deque<Integer> increasing = new LinkedList<Integer>(); // To keep track of Max_value index
Deque<Integer> decreasing = new LinkedList<Integer>(); // To keep track of Min_value index
int i = 0 ;
... | class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
int max_ans = 0;
map <int, int> mp;
int j = 0;
for(int i = 0 ; i < nums.size() ; i++) {
mp[nums[i]] ++;
while( mp.size() > 0 && abs(mp.rbegin()->first - mp.begin()->first) > limit)... | /**
* @param {number[]} nums
* @param {number} limit
* @return {number}
*/
var longestSubarray = function(nums, limit) {
const maxQueue = [];
const minQueue = [];
let start = 0;
let res = 0;
for(let end = 0; end < nums.length; end ++) {
const num = nums[end];
while(maxQueue.lengt... | Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit |
Return the result of evaluating a given boolean expression, represented as a string.
An expression can either be:
"t", evaluating to True;
"f", evaluating to False;
"!(expr)", evaluating to the logical NOT of the inner expression expr;
"&(expr1,expr2,...)", evaluating to the logical AND of 2 or more inner ex... | class Solution:
def parseBoolExpr(self, expression: str) -> bool:
# expresssion map
opMap = {"!" : "!", "|" : "|" , "&" : "&"}
expMap = {"t" : True, "f" : False}
expStack = []
opStack = []
ans = 0
i = 0
while i < len(expression):
... | class Solution {
int pos = 0;
public boolean parseBoolExpr(String s) {
pos = 0;
return solve(s, '-');
}
public boolean solve(String s, char prev_sign) {
boolean res = s.charAt(pos) == 'f' ? false : true;
char cur_sign = ' ';
int flag_res_ini... | class Solution {
pair<bool,int> dfs(string &e, int idx){
bool res;
if(e[idx]=='!'){
auto [a,b]=dfs(e, idx+2);
return {!a,b+3};
}else if(e[idx]=='&'){
int len=2;
res=true;
idx+=2;
while(e[idx]!=')'){
if(e[... | var parseBoolExpr = function(expression) {
let sol, stack = [],
op={t:true, f:false};
for(let i=0; i<expression.length; i++){
if(expression[i] != ")"){
if(expression[i]!==",")stack.push(expression[i]);
}else{
let findings = [], ko;;
while(stack.slice(... | Parsing A Boolean Expression |
Design a stack which supports the following operations.
Implement the CustomStack class:
CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.
void push(int x) Adds x to the top of the stack if the stac... | class CustomStack:
def __init__(self, maxSize: int):
self.size = maxSize
self.stack = []
def push(self, x: int) -> None:
if self.size > len(self.stack):
self.stack.append(x)
def pop(self) -> int:
if self.stack:
return self.stack.pop()
return -1
def increment(self, k: int, val: int) -... | class CustomStack {
int[] stack;
int top;
public CustomStack(int maxSize) {
//intialise the stack and the top
stack= new int[maxSize];
top=-1;
}
public void push(int x) {
// if the stack is full just skip
if( top==stack.length-1) return;
//add t... | class CustomStack {
int *data;
int nextIndex;
int capacity;
public:
CustomStack(int maxSize) {
data = new int[maxSize];
nextIndex = 0;
capacity = maxSize;
}
void push(int x) {
if(nextIndex == capacity){
return;
}
data[nextIndex] = x;
... | var CustomStack = function(maxSize) {
this.stack = new Array(maxSize).fill(-1);
this.maxSize = maxSize;
this.size = 0;
};
CustomStack.prototype.push = function(x) {
if(this.size < this.maxSize){
this.stack[this.size] = x;
this.size++;
}
};
CustomStack.prototype.pop = function() {
... | Design a Stack With Increment Operation |
We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces and ended up with the string s.
For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)".
Return a list of strings representing all possibilities for what our original coor... | class Solution(object):
def ambiguousCoordinates(self, s):
"""
:type s: str
:rtype: List[str]
"""
def _isValidSplit(s):
return False if len(s)>1 and re.match('/^[0]+$/',s) else True
def _isValidNum(ipart,fpart):
return False if (len(ipart)>1 a... | class Solution {
public List<String> ret;
public List<String> ans;
public List<String> ambiguousCoordinates(String s) {
ret=new ArrayList<>();
ans=new ArrayList<>();
String start=s.substring(0,2);
util(s,1);
fun();
return ans;
}
//putting comma
... | class Solution {
public:
vector<string> check(string s){
int n = s.size();
vector<string> res;
if(s[0] == '0'){
if(n == 1)
res.push_back(s);
else{
if(s[n-1] == '0')
return res;
s.inse... | var ambiguousCoordinates = function(S) {
let ans = [], xPoss
const process = (str, xy) => {
if (xy)
for (let x of xPoss)
ans.push(`(${x}, ${str})`)
else xPoss.push(str)
}
const parse = (str, xy) => {
if (str.length === 1 || str[0] !== "0")
... | Ambiguous Coordinates |
You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanati... | class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
dec = {}
c = 0
res=''
for i in indices:
dec[i] = s[c]
c += 1
# dec = {"4":"c","5":"o","6":"d","7":"e","0":"l","2":"e","1":"e","3":"t"}
for x in range(len(indices)):
... | class Solution {
public String restoreString(String s, int[] indices) {
char[] ch = new char[s.length()];
for(int i = 0 ; i< s.length() ; i ++){
ch[indices[i]]=s.charAt(i);
}
return new String (ch);
}
} | class Solution {
public:
string restoreString(string s, vector<int>& indices) {
string ans = s;
for(int i=0 ; i<s.size() ; i++){
ans[indices[i]] = s[i];
}
return ans;
}
}; | var restoreString = function(s, indices) {
const result = []
for(let i=0; i<s.length; i++) {
const letter = s[i]
const index = indices[i]
result[index] = letter
}
return result.join('')
}; | Shuffle String |
You are given an integer array target and an integer n.
You have an empty stack with the two following operations:
"Push": pushes an integer to the top of the stack.
"Pop": removes the integer on the top of the stack.
You also have a stream of the integers in the range [1, n].
Use the two stack operations to ma... | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
temp = []
result = []
x = target[-1]
for i in range(1,x+1):
temp.append(i)
for i in range(len(temp)):
if temp[i] in target:
result.append("Push")
... | class Solution {
public List<String> buildArray(int[] target, int n) {
List<String> result=new ArrayList<>();
int i=1,j=0;
while(j<target.length)
{
result.add("Push");
if(i==target[j]){
j++;
}else{
result.add("Pop");
... | class Solution {
public:
vector<string> buildArray(vector<int>& target, int n) {
vector<string>ans;
int l=target.size(), count=0,ind=0; // ind is index of the target array
for(int i=1;i<=n;i++){
if(count==l) break;
if(target[ind]!=i){
ans.push_back("P... | /**
* @param {number[]} target
* @param {number} n
* @return {string[]}
*/
var buildArray = function(target, n) {
let arr = [];
let index = 0;
for(let i = 1; i <= target[target.length-1];i++){
if(target[index] == i){
arr.push('Push');
index++;
}else{
a... | Build an Array With Stack Operations |
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Example 1:
Input: root =... | # 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 deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
def find_inorder(root, key):
... | class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root==null) return null;
if(key<root.val){
root.left = deleteNode(root.left,key);
return root;
}
else if(key>root.val){
root.righ... | class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root)
if(key < root->val) root->left = deleteNode(root->left, key); //We frecursively call the function until we find the target node
else if(key > root->val) root->right = deleteNode(root->right, key); ... | /**
* 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)
* }
*/
const getLeftMostNode=(root)=>{
if(!root)return null;
let node=get... | Delete Node in a BST |
You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The ... | class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
scores_ids = []
for i in range(len(score)):
scores_ids.append((score[i], i))
scores_ids.sort(reverse=True)
ans = [0] * len(scores_ids)
for i in range(len(scores_ids)):
ans[sco... | class Solution {
public String[] findRelativeRanks(int[] score) {
String[] res = new String[score.length];
TreeMap<Integer, Integer> map = new TreeMap<>();
for(int i = 0; i < score.length; i++) map.put(score[i], i);
int rank = score.length;
for(Map.Entry<Integer, Integer> p... | class Solution {
public:
vector<string> findRelativeRanks(vector<int>& score) {
int n=score.size();
vector<string> vs(n);
unordered_map<int,int> mp;
for(int i=0; i<score.size(); i++){
mp[score[i]]=i;
}
sort(score.begin(),score.end(),greater<int>());
... | var findRelativeRanks = function(score) {
let output=score.slice(0);
let map={};
score.sort((a,b)=>b-a).forEach((v,i)=>map[v]=i+1);
for(let item in map){
if(map[item]==1){map[item]="Gold Medal"};
if(map[item]==2){map[item]="Silver Medal"};
if(map[item]==3){map[item]="Bronze Medal... | Relative Ranks |
You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day.
A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day o... | import sys
class Solution:
def getDescentPeriods(self, prices: List[int]) -> int:
def calculate(k,ans):
if k>1:
ans+=((k-1)*(k))//2
#Sum of Natural Numbers
return ans
else:
return ans
end = 0
start = 0
prev... | class Solution {
public long getDescentPeriods(int[] prices) {
int i=0;
int j=1;
long ans=1;
while(j<prices.length){
if( prices[j-1]-prices[j]==1){
//It means that j(current element) can be part of previous subarrays (j-i)
//and can also start a su... | class Solution {
public:
long long getDescentPeriods(vector<int>& prices) {
long long ans = 0;
long long temp = 0;
for(int i=1; i<prices.size(); i++){
if(prices[i - 1] - prices[i] == 1){
temp++;
ans += temp;
}
else{
... | var getDescentPeriods = function(prices) {
const n = prices.length;
let left = 0;
let totRes = 0;
while (left < n) {
let count = 1;
let right = left + 1;
while (right < n && prices[right] + 1 === prices[right - 1]) {
count += (right - left + 1);
++righ... | Number of Smooth Descent Periods of a Stock |
You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is ... | class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
m = defaultdict(list)
for a, b, p in edges:
m[a].append((p, b))
m[b].append((p, a))
vis = set()
queue = []
heappush(queue, (0, 0))
edgevis = set()
... | class Solution {
public int reachableNodes(int[][] edges, int maxMoves, int n) {
int[][] graph = new int[n][n];
for ( int[] t: graph ) {
Arrays.fill(t, -1);
}
for ( int[] t: edges ) {
graph[t[0]][t[1]] = t[2];
graph[t[1]][t[0]] = t[2];
}
... | class Solution {
public:
int reachableNodes(vector<vector<int>>& edges, int maxMoves, int n) {
const int INF = 1e8;
vector<vector<pair<int,int>> g(n);
for(auto i: edges){
g[i[0]].push_back({i[1],i[2]});
g[i[1]].push_back({i[0],i[2]});
}
priority_queue<pair<int,int>, vector<pair<int,int>>, greater... | var reachableNodes = function(edges, maxMoves, n) {
const g = Array.from({length: n}, () => []);
for(let [u, v, cnt] of edges) {
g[u].push([v, cnt + 1]);
g[v].push([u, cnt + 1]);
}
// find min budget to reach from 0 to all nodes
const budget = new Array(n).fill(Infinity);
... | Reachable Nodes In Subdivided Graph |
You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.
You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).
For example, if w ... | class Solution(object):
def __init__(self, w):
"""
:type w: List[int]
"""
#Cumulative sum
self.list = [0] * len(w)
s = 0
for i, n in enumerate(w):
s += n
self.list[i] = s
def pickIndex(self):
"""
:rtype: int
"""
return bisect_left(self.list, random.randint(1, self.list[-1]))
# Your So... | class Solution {
private int[] prefixSum;
private Random random;
public Solution(int[] w) {
for (int i = 1; i < w.length; i++)
w[i] += w[i - 1];
prefixSum = w;
random = new Random();
}
public int pickIndex() {
int num = 1 + random.nextInt(prefixSum[pref... | class Solution {
public:
vector<int> cumW;
Solution(vector<int>& w) {
// initialising random seeder
srand(time(NULL));
// populating the cumulative weights vector
cumW.resize(w.size());
cumW[0] = w[0];
for (int i = 1; i < w.size(); i++) cumW[i] = cumW[i - 1] + w... | class Solution {
constructor(nums) {
this.map = new Map();
this.sum = 0;
nums.forEach((num, i) => {
this.sum += num;
this.map.set(this.sum, i);
})
}
pickIndex = function() {
const random_sum = Math.floor(Math.random() * this.sum);
... | Random Pick with Weight |
Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:
Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.
Ret... | class Solution:
def constructArray(self, n: int, k: int) -> List[int]:
# n = 8, k = 5
# 1 2 3 8 4 7 5 6
# 1 1 5 4 3 2 1
res = list(range(1,n-k+1))
sign, val = 1, k
for i in range(k):
res.append(res[-1]+sign*val)
sign *= -1
val -= 1
... | class Solution {
public int[] constructArray(int n, int k) {
int [] result = new int[n];
result[0] = 1;
int sign = 1;
for(int i = 1 ; i < n; i++, k--){
if(k > 0){
result[i] = result[i-1] + k * sign;
sign *= -1;
}
els... | class Solution {
public:
vector<int> constructArray(int n, int k) {
int diff = n - k;
int lo = 1;
int hi = n;
vector<int> out;
int i = 0;
// we generate a difference of 1 between subsequent elements for the first n-k times.
while(i < diff){
out.push_bac... | var constructArray = function(n, k) {
const result = [];
let left = 1;
let right = n;
for (let index = 0; index < n; index++) {
if (k === 1) {
result.push(left++);
continue;
}
const num = k & 1 ? left++ : right--;
result.push(num);
k -= 1;... | Beautiful Arrangement II |
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its len... | class Solution(object):
def longestConsecutive(self, nums):
ans=0
nums=set(nums)
count=0
for i in nums:
if i-1 not in nums:
j=i
count=0
while j in nums:
count+=1
j+=1
a... | class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> storage = new HashSet();
for(int i = 0; i < nums.length; i++){
storage.add(nums[i]);
}
int maxL = 0;
for(int i = 0; i < nums.length; i++){
... | class Solution {
public:
int longestConsecutive(vector<int>& nums) {
set<int> hashSet;
int longestConsecutiveSequence = 0;
for(auto it : nums){
hashSet.insert(it);
}
for(auto it : nums){
if(!hashSet.cou... | /**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
if(nums.length === 1){
return 1
}
if(nums.length === 0){
return 0
}
nums.sort((a, b) => a - b)
let result = 1
let streak = 1
let i = 0
while(i < nums.length - 1){
if(nums[i] == nums[i + 1]) {
... | Longest Consecutive Sequence |
You are given a string number representing a positive integer and a character digit.
Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in numb... | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
# Initializing the last index as zero
last_index = 0
#iterating each number to find the occurences, \
# and to find if the number is greater than the next element \
for num in range(1, ... | class Solution {
public String removeDigit(String number, char digit) {
List<String> digits = new ArrayList<>();
for (int i = 0; i < number.length(); i++) {
if (number.charAt(i) == digit) {
String stringWithoutDigit = number.substring(0, i) + number.substring(i + 1);
... | class Solution {
public:
string removeDigit(string number, char digit) {
string res = "";
for(int i=0; i<number.size(); i++){
if(number[i] == digit){
string temp = number.substr(0, i) + number.substr(i+1);
res = max(res, temp);
}
}
... | /**
* @param {string} number
* @param {character} digit
* @return {string}
*/
var removeDigit = function(number, digit) {
let str = [];
let flag = 0;
for (let i = 0; i < number.length; i++) {
if (number[i] == digit ) {
let temp = number.substring(0, i) + number.substring(i+1);
... | Remove Digit From Number to Maximize Result |
Given a string s, reverse the string according to the following rules:
All the characters that are not English letters remain in the same position.
All the English letters (lowercase or uppercase) should be reversed.
Return s after reversing it.
Example 1:
Input: s = "ab-cd"
Output: "dc-ba"
Example 2:
Inp... | class Solution:
def reverseOnlyLetters(self, s: str) -> str:
st,sp=[],[]
for i,ch in enumerate(s):
if ch.isalpha():
st.append(ch)
else:
sp.append([i,ch])
st=st[::-1]
for i in sp:
st.insert(i[0],i[1])
return (... | class Solution {
public String reverseOnlyLetters(String s) {
// converting the string to the charArray...
char[] ch = s.toCharArray();
int start = 0;
int end = s.length()-1;
// Storing all the english alphabets in a hashmap so that the searching becomes easy...
Has... | class Solution {
public:
string reverseOnlyLetters(string s) {
int a=0,b=s.size()-1;
for(;a<b;)
{
if(((s[a]>='a'&&s[a]<='z')||(s[a]>='A'&&s[a]<='Z'))&&((s[b]>='a'&&s[b]<='z')||(s[b]>='A'&&s[b]<='Z')))
{
char z=s[a];
s[a]=s[b];
... | var reverseOnlyLetters = function(s) {
let valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
let arr = s.split('')
let r = arr.length - 1;
let l = 0;
while (l < r) {
while (!valid.includes(arr[l]) && l < r) {
l++;
continue;
}
... | Reverse Only Letters |
You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:
2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.
1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is ... | class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
n = len(nums)
max_dp = [0] * n
min_dp = [float(inf)] * n
max_dp[0] = nums[0]
min_dp[-1] = nums[-1]
for i in range(1, n):
max_dp[i] = max(nums[i], max_dp[i-1])
fo... | class Solution {
public int sumOfBeauties(int[] nums) {
boolean[] left = new boolean[nums.length];
boolean[] right = new boolean[nums.length];
left[0] = true;
int leftMax = nums[0];
for(int i = 1; i < nums.length; i++) {
if(nums[i] > leftMax) {
le... | class Solution {
public:
int sumOfBeauties(vector<int>& nums) {
int n=nums.size();
vector<int>right;
vector<int>left;
int low=nums[0];
for(int i=0;i<nums.size();i++){
left.push_back(low);
low=max(low,nums[i]);
}
low=nums[n-... | /**
* @param {number[]} nums
* @return {number}
*/
var sumOfBeauties = function(nums) {
let min = nums[0], max = Infinity, maxArr = [], total = 0;
// Creating an array, which will keep the record of minimum values from last index
for(let i=nums.length-1; i>1; i--) {
if(nums[i] < max) max = nums[... | Sum of Beauty in the Array |
You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.
If targetCapacity liters of water are measurable, you must have targetCapacity liters of wa... | class Solution:
def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:
n1, n2, t = jug1Capacity, jug2Capacity, targetCapacity
if n1 == t or n2 == t or n1 + n2 == t:
return True
if n1 + n2 < t:
return False
if n1 < n2:
... | class Solution {
private static int gcd(int a,int b){
if(b==0)return a;
return gcd(b,a%b);
}
public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
if(targetCapacity>jug1Capacity+jug2Capacity){
return false;
}
int g=gcd(ju... | class Solution {
public:
bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
if(targetCapacity > jug1Capacity + jug2Capacity)
return false;
vector<int> dp(jug1Capacity + jug2Capacity + 1, -1);
return helper(0, jug1Capacity, jug2Capacit... | var canMeasureWater = function(jug1Capacity, jug2Capacity, targetCapacity) {
const gcd = (x, y) => y === 0 ? x : gcd(y, x % y);
return jug1Capacity + jug2Capacity >= targetCapacity &&
targetCapacity % gcd(jug1Capacity, jug2Capacity) === 0;
}; | Water and Jug Problem |
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Example 1:
Input: nums = [3,2,3]
Output: [3]
Example 2:
Input: nums = [1]
Output: [1]
Example 3:
Input: nums = [1,2]
Output: [1,2]
Constraints:
1 <= nums.length <= 5 * 104
-109 <= nums[i] <= ... | class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
#Boyer Moore Voting Algo (As used in ME1 ques)
#now we can observe that there cannot be more than two elements occuring more than n//3 times in an array
#so find two majority elements(me=majority element)
... | class Solution {
public List<Integer> majorityElement(int[] nums) {
int val1 = nums[0], val2 = nums[0], cnt1 = 1, cnt2 = 0;
for(int i = 1; i < nums.length; i++){
if(val1 == nums[i]){
cnt1++;
} else if(val2 == nums[i]){
cnt2++;
} els... | class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int n = nums.size();
vector<int> result;
int num1 = -1 , num2 = -1 , count1 = 0 , count2 = 0;
for(auto it : nums){
if(num1 == it) ++count1;
else if(num2 == it) ++count2;
... | /**
* @param {number[]} nums
* @return {number[]}
*/
var majorityElement = function(nums) {
const objElement = {};
const timesVar = Math.floor(nums.length/3);
const resultSet = new Set();
for(var indexI=0; indexI<nums.length; indexI++){
if(objElement[nums[indexI]]) {
objElement... | Majority Element II |
You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.
You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The fin... | class Solution:
def reformatNumber(self, number: str) -> str:
s = number.replace(" ", "").replace("-", "")
pieces = list()
while s:
if len(s) == 2:
pieces.append(s)
break
elif len(s) == 4:
pieces.append(s[:2])
... | class Solution {
String modifiedNumber="";
public String reformatNumber(String number) {
modifiedNumber=number.replace(" ","");
modifiedNumber=modifiedNumber.replace("-","");
int l=modifiedNumber.length();
if(l<=3){
return modifiedNumber;
} else if(l==4){
... | class Solution {
public:
string reformatNumber(string number) {
string temp; // stores the digits from string number
string ans; //stores final answer
int n = number.size();
for(auto ch:number)
if(isdigit(ch)) temp += ch;
int len = temp.size();
int i = ... | var reformatNumber = function(number) {
let numArr = number.replace(/-/g,'').replace(/ /g,'').split('')
let res = ''
while(numArr.length >= 4){
numArr.length == 4 ?
res += numArr.splice(0,2).join('') +'-'+numArr.splice(0,2).join('') :
res += numArr.splice(0,3).join('') + '-'
... | Reformat Phone Number |
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
A ... | #Baraa
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
"""
what is (x * (x + 1)) // 2? this is series sum formula between n and 1
which means: n + (n - 1) + (n - 2) + (n - 3) .... + 1
when we have a total number of 10 elements that form an arithmetic sum... | class Solution {
public int numberOfArithmeticSlices(int[] nums) {
int n = nums.length;
if (n < 3) {
return 0;
}
int[] dp = new int[n - 1];
dp[0] = nums[1] - nums[0];
for (int i = 2; i < n; i++) {
dp[i - 1] = nums[i] - nums[i - 1];
}
... | class Solution {
public:
int numberOfArithmeticSlices(vector<int>& nums) {
int n=nums.size(),i,j,count=0,comm_diff;
for(i=0;i<=n-3;i++)
{
comm_diff = nums[i+1]-nums[i];
for(j=i+1;j<n;j++)
{
if(nums[j]-nums[j-1]==comm_diff)
{... | /**
* @param {number[]} nums
* @return {number}
*/
var numberOfArithmeticSlices = function(nums) {
nums.push(-2000)
let count = 0
let dist = nums[1]-nums[0]
let start = 0
for (let i = 1; i < nums.length; i++) {
if (nums[i]-nums[i-1] !== dist) {
let len = i... | Arithmetic Slices |
Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.
Example 1:
Input: n = 2, m = 3
Output: 3
Explanation: 3 squares are necessary to cover the rectangle.
2 (squares of 1x1)
1 (square of 2x2)
Example 2:
Input: n = 5, m = 8
Output: 5
Example 3:
... | class Solution:
def tilingRectangle(self, n: int, m: int) -> int:
# try brute force backtracking?
board = [[0 for _ in range(n)] for _ in range(m)]
ans = math.inf
def bt(counts):
nonlocal ans
if counts >= ans:
return
pos = None
found = Fals... | class Solution {
int ret; // store the final result
int m, n; // m is the height, and n is the width
// Note: original signature is changed from n,m to m,n
public int tilingRectangle(int m, int n) {
this.m = m;
this.n = n;
this.ret = m * n; // initilize the result as m*n if cut r... | class Solution {
public:
int solve(int n, int m, vector<vector<int>>& dp) {
if(n<0 || m<0) return 0;
if(m==n) return 1;
// this is special case
if((m==13 && n==11) || (m==11 && n==13)) return dp[n][m]=6;
if(dp[n][m]!=0) return dp[n][m];
int ... | var tilingRectangle = function(n, m) {
const queue = [[new Array(n).fill(0), 0]];
while (true) {
const [curr, numSquares] = queue.shift();
let min = { height: Infinity, start: Infinity, end: Infinity }
for (let i = 0; i < n; i++) {
if (curr[i] < min.height) {
min.height = curr[i];
... | Tiling a Rectangle with the Fewest Squares |
You are given a string s consisting of n characters which are either 'X' or 'O'.
A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.
Return the minimum number of moves required so that all the characte... | class Solution:
def minimumMoves(self, s: str) -> int:
i, m = 0, 0
l = len(s)
while i < l:
if s[i] != 'X':
i += 1
elif 'X' not in s[i:i+1]:
i += 2
elif 'X' in s[i:i+2]:
m += 1
i += 3
... | class Solution {
public int minimumMoves(String s) {
int i=0;
int step=0;
while(i<s.length()){
if(s.charAt(i)=='X'){
i=i+3;
step++;
}
else{
i++;
}
}
return step;
}
} | class Solution {
public:
int minimumMoves(string s) {
int count=0;
int i=0;
for(int i=0;i<s.size();){
if(s[i]=='O'){
// continue;
i++;}
else{
count++;
i+=3;
}
}
return count;
... | var minimumMoves = function(s) {
let move = 0;
let i = 0;
while(i<s.length){
let char = s[i];
// incrementing the index if we already have 'O'
if(char== 'O'){
i++;
}
// incrementing the move and index by 3 (Per move = 3 characters)
if(char== 'X'){
... | Minimum Moves to Convert String |
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and uses only constant extra space.
Example 1:
... | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
dictx = {}
for each in nums:
if each not in dictx:
dictx[each] = 1
else:
return each | class Solution {
public int findDuplicate(int[] nums) {
int i = 0;
while (i < nums.length) {
if (nums[i] != i + 1) {
int correct = nums[i] - 1;
if (nums[i] != nums[correct]) {
swap(nums, i , correct);
} else {
... | // Please upvote if it helps
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int low = 1, high = nums.size() - 1, cnt;
while(low <= high)
{
int mid = low + (high - low) / 2;
cnt = 0;
// cnt number less than equal to mid
... | var findDuplicate = function(nums) {
let dup = new Map();
for(let val of nums){
if(dup.has(val)){
dup.set(val, dup.get(val) + 1);
return val;
}
else
dup.set(val, 1);
}
}; | Find the Duplicate Number |
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to ... | class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.strip().split()[-1]) | class Solution {
public int lengthOfLastWord(String s) {
int j=s.length()-1,len=0; boolean flag=true;
while(j>=0 && (flag || (!flag && s.charAt(j)!=' ')))
if(s.charAt(j--)!=' '){
flag=false;
len++;
}
return len;
}
} | class Solution {
public:
int lengthOfLastWord(string s) {
int count = 0;
int n = s.size();
int i = n-1;
while(i>=0){
if(s[i]==' '){
i--;
if(count >0){
break;
}
}
else{
... | var lengthOfLastWord = function(s) {
s = s.split(" ");
if(s[s.length-1] == ``)
{
for(var i = s.length-1; i >= 0; i-- )
{
if(s[i].length > 0)
{
return s[i].length;
}
}
}
else
{
return s[s.length-1].length;
}
}... | Length of Last Word |
You are given a 0-indexed integer array nums of length n.
The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.
Return the index with the mini... | from itertools import accumulate
class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
size = len(nums)
nums[::] = list(accumulate(nums))
total = nums[-1]
min_tuple = [0, sys.maxsize]
for (i, n) in enumerate(nums):
i = i +... | class Solution {
public int minimumAverageDifference(int[] nums) {
if(nums.length == 1){
return 0;
}
int idx = -1;
long min = Integer.MAX_VALUE;
long suml = nums[0];
long sumr = 0;
for(int i = 1; i < nums.length; i++){
sumr += nums[i];
... | class Solution {
public:
int minimumAverageDifference(vector<int>& nums) {
int n(size(nums)), minAverageDifference(INT_MAX), index;
long long sumFromFront(0), sumFromEnd(0);
for (auto& num : nums) sumFromEnd += num;
for (int i=0; i<n; i++) {
sumFromFront += nums[i];
... | ```/**
* @param {number[]} nums
* @return {number}
*/
var minimumAverageDifference = function(nums) {
if (nums.length == 1) return 0;
let mins = 100000, resultIndex, leftTotal = 0;
let rightTotal = nums.reduce((a,b)=>a + b);
let numLength = nums.length;
nums.forEach((data, index)=> {
lef... | Minimum Average Difference |
You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.
Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list.
Example 1:
Input: head = [0,1,2,3], n... | class Solution:
def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
d,count={},0
for num in nums:
d[num] = 0
while head:
if head.val in d:
head = head.next
while head and head.val in d:
head =... | class Solution {
public int numComponents(ListNode head, int[] nums) {
int count=0;
HashSet<Integer> set=new HashSet();
for(int i=0;i<nums.length;i++)
{
set.add(nums[i]);
}
while(head!=null)
{
if(set.contains(head.val))
{
... | class Solution {
public:
int numComponents(ListNode* head, vector<int>& nums)
{
unordered_set<int> s;
for(auto &x:nums)
s.insert(x);
int count=0;
while(head!=NULL)
{
if(s.find(head->val)!=s.end()) count++;
while(head!=NULL && s.find(hea... | var numComponents = function(head, nums) {
let broken = true, count = 0;
while (head) {
if (nums.includes(head.val) && broken) {
count++;
broken = false;
}
else if (!nums.includes(head.val)) {
broken = true;
}
// reset head as next
... | Linked List Components |
You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.
There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c.
For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.
For every odd in... | class Solution(object):
def replaceDigits(self, s):
"""
:type s: str
:rtype: str
"""
res = []
for i in range(len(s)):
if i % 2 == 0:
res.append(s[i])
if i % 2 == 1:
res.append( chr(ord(s[i-1]) + int(s[i])) )
... | class Solution {
public String replaceDigits(String s) {
char[] str = s.toCharArray();
for(int i=0;i<str.length;i++){
if(Character.isDigit(str[i])){
str[i] = shift(str[i-1],str[i]);
}
}
return String.valueOf(str);
}
char shift(char lett... | class Solution {
public:
string replaceDigits(string s) {
for(int i=1;i<s.size();i+=2){
s[i]=s[i-1]+(s[i]-'0'); //or s[i] += s[i-1] - '0';
}
return s;
}
}; | var replaceDigits = function(s) {
let res = ''
for(let i = 0; i < s.length; i++){
if(i % 2 !== 0){
res += String.fromCharCode(s[i - 1].charCodeAt() + parseInt(s[i]))
} else{
res += s[i]
}
}
return res;
}; | Replace All Digits with Characters |
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
... | class LockingTree:
def __init__(self, parent: List[int]):
self.p = collections.defaultdict(lambda: -2)
self.c = collections.defaultdict(list)
for i, p in enumerate(parent):
self.c[p].append(i)
self.p[i] = p
self.user = collections.defaultdict(set)
sel... | class LockingTree {
int[] p;
Map<Integer, Integer> map = new HashMap<>();
Map<Integer, List<Integer>> children = new HashMap<>();
public LockingTree(int[] parent) {
p = parent;
for(int i = 0; i < p.length; i ++) {
children.put(i, new ArrayList<>());
}
for(int ... | class LockingTree {
public:
unordered_map<int,int> locks_aquired;
vector<vector<int>> graph;
unordered_map<int,int> parents;
LockingTree(vector<int>& parent)
{
int n=parent.size();
graph = vector<vector<int> >(n);
parents[0] = -1 ; // since parent of node 0 is... | var LockingTree = function(parent) {
this.parents = parent;
this.children = [];
this.locked = new Map();
for (let i = 0; i < this.parents.length; ++i) {
this.children[i] = [];
}
for (let i = 1; i < this.parents.length; ++i) {
const parent = this.parents[i];
... | Operations on Tree |
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the ParkingSystem class:
ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for ea... | class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self.vehicle =[big,medium,small]
def addCar(self, carType: int) -> bool:
if carType == 1 :
if self.vehicle[0] > 0:
self.vehicle[0]-=1
return True
elif carType == 2:
... | class ParkingSystem {
private int[] size;
public ParkingSystem(int big, int medium, int small) {
this.size = new int[]{big, medium, small};
}
public boolean addCar(int carType) {
return size[carType-1]-->0;
}
} | class ParkingSystem {
public: vector<int> vehicle;
public:
ParkingSystem(int big, int medium, int small) {
vehicle = {big, medium, small};
}
bool addCar(int carType) {
return vehicle[carType - 1]-- > 0;
} | var ParkingSystem = function(big, medium, small) {
this.count = [big, medium, small];
};
/**
* @param {number} carType
* @return {boolean}
*/
ParkingSystem.prototype.addCar = function(carType) {
return this.count[carType - 1]-- > 0;
};
/**
* Your ParkingSystem object will be instantiated and called as suc... | Design Parking System |
Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanat... | from itertools import combinations
class Solution:
def numIdenticalPairs(self, nums) -> int:
res = 0
nums_set = set(nums)
nums_coppy = nums
for number in nums_set:
number_found = []
deleted = 0
while True:
try:
found =... | class Solution {
public int numIdenticalPairs(int[] nums) {
int len =nums.length;
int counter=0;
for (int i =0;i<len;i++){
for (int j=i+1;j<len;j++){
if(nums[i]==nums[j]){
counter++;
}
}
... | class Solution {
public:
int numIdenticalPairs(vector<int>& nums) {
int cnt = 0;
for(int i=0 ; i<nums.size() ; i++){
for(int j=i+1 ; j<nums.size() ; j++){
if(nums[i] == nums[j]){
cnt++;
}
}
}
return cnt;
... | var numIdenticalPairs = function(nums) {
let counter = 0;
let map = {};
for(let num of nums) {
if(map[num]) {
counter += map[num];
map[num]++;
} else {
map[num] = 1;
}
}
return counter;
}; | Number of Good Pairs |
You are given the head of a linked list.
The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words,
The 1st node is assigned to the first group.
The... | class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
group = 2
tail = head # tail of previous group
while tail and tail.next:
cnt = 1 # actual size of the current group
cur = tail.next # first node of the current group
... | // This Question can be solved easily using two standard methods of LinkedList
// 1) addFirst (it adds node in front of the LinkedList)
// 2) addLast (it adds node in end of the LinkedList)
class Solution {
static ListNode oh;
static ListNode ot;
static ListNode th;
static ListNode tt;
public Lis... | class Solution {
public:
// Function to reverse a linked list
ListNode* reverseList(ListNode* head) {
if(!head)
return head;
ListNode* prev = NULL;
while(head) {
ListNode* temp = head -> next;
head -> next = prev;
prev = head;
... | var reverseEvenLengthGroups = function(head) {
let groupSize = 2;
let start = head;
let prev = head;
let curr = head.next;
let count = 0;
while (curr != null) {
if (count === groupSize) {
if (groupSize % 2 === 0) { // we only reverse when it is even
co... | Reverse Nodes in Even Length Groups |
There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0.
You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return... | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
return max(accumulate([0]+gain)) | class Solution {
public int largestAltitude(int[] gain) {
int max_alt=0;
int curr_alt=0;
for(int i=0;i<gain.length;i++){
curr_alt+=gain[i];
max_alt=Math.max(curr_alt, max_alt);
}
return max_alt;
}
}
//TC: O(n), SC: O(1) | class Solution {
public:
int largestAltitude(vector<int>& gain) {
int maxAltitude = 0;
int currentAltitude = 0;
for (int i = 0; i < gain.size(); i++) {
currentAltitude += gain[i];
maxAltitude = max(maxAltitude, currentAltitude);
}
ret... | var largestAltitude = function(gain) {
let points = [0]
let highest = 0
for (let i = 0; i < gain.length; i++) {
let point = points[i] + gain[i]
points.push(point)
if (point > highest) highest = point
}
return highest
}; | Find the Highest Altitude |
You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.
Return the order of the largest axis-aligned plus sign of 1's contained in grid. I... | class Solution:
def orderOfLargestPlusSign(self, n: int, mines: list[list[int]]) -> int:
matrix = [1] * n
aux = {}
hasOne = False
for i in range(0,n):
matrix[i] = [1] * n
for mine in mines:
matrix[mine[0]][mine[1]] = 0
for i in range(0,n):
... | class Solution {
public int orderOfLargestPlusSign(int n, int[][] mines) {
// Create the matrix
int[][] arr = new int[n][n];
for(int[] subArray : arr) {
Arrays.fill(subArray, 1);
}
for(int i = 0; i < mines.length; i++) {
arr[mines[i][0]][mines[i][1]] ... | class Solution {
public:
int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {
//jai shri ram
int ans=0;
vector<bool>block(25*int(1e4)+1,0);
vector<vector<int>>dp(n,vector<int>(n,0));
for(auto x:mines){
int a=x[0],b=x[1];
block[a*n+b]=true;
... | /**
* @param {number} n
* @param {number[][]} mines
* @return {number}
*/
var orderOfLargestPlusSign = function(n, mines) {
// create n * n as a table, and each grid fill the maximum number
const t = new Array(n).fill(0).map(() => new Array(n).fill(n));
// insert `0` to the grid in table according the ... | Largest Plus Sign |
You are given a 0-indexed integer array nums and a target element target.
A target index is an index i such that nums[i] == target.
Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasi... | class Solution:
def targetIndices(self, nums, target):
ans = []
for i,num in enumerate(sorted(nums)):
if num == target: ans.append(i)
return ans | class Solution {
/** Algorithm:
- Parse the array once and count how many are lesser than target and how many are equal
- DO NOT sort the array as we don't need it sorted.
Just to know how many are lesser and how many are equal. O(N) better than O(NlogN - sorting)
- The response li... | class Solution {
public:
vector<int> targetIndices(vector<int>& nums, int target) {
vector<int> result;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++){
if(nums[i]==target) result.push_back(i);
}
return result;
}
}; | function binarySearch(lists, sorted, low, high, target){
if(low > high) return;
const mid = low + Math.floor((high - low) / 2);
if(sorted[mid] === target){
lists.push(mid);
}
binarySearch(lists, sorted, low, mid-1, target);
binarySearch(lists, sorted, mid+1, high, target);
}
var targetIn... | Find Target Indices After Sorting Array |
You have a set which contains all positive integers [1, 2, 3, 4, 5, ...].
Implement the SmallestInfiniteSet class:
SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.
int popSmallest() Removes and returns the smallest integer contained in the infinite set.
void addBa... | class SmallestInfiniteSet:
def __init__(self):
self.index = 1
self.heap = []
def popSmallest(self) -> int:
if self.heap:
return heapq.heappop(self.heap)
self.index += 1
return self.index-1
def addBack(self, num: int) -> None:
if self.index > num... | class SmallestInfiniteSet {
private PriorityQueue<Integer> q;
private int index;
public SmallestInfiniteSet() {
q = new PriorityQueue<Integer>();
index = 1;
}
public int popSmallest() {
if (q.size()>0){
return q.poll();
}
return index++;
}... | class SmallestInfiniteSet {
public:
int cur;
set<int> s;
SmallestInfiniteSet() {
cur=1;
}
int popSmallest() {
if(s.size()){
int res=*s.begin(); s.erase(res);
return res;
}else{
cur+=1;
return cur-1;
}
}
void ad... | var SmallestInfiniteSet = function() {
const s = new Set();
this.s = s;
for(let i = 1; i <= 1000; i++) s.add(i);
};
/**
* @return {number}
*/
SmallestInfiniteSet.prototype.popSmallest = function() {
const min = Math.min(...Array.from(this.s));
this.s.delete(min);
return min;
};
/**
* @param... | Smallest Number in Infinite Set |
You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.
Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.
A chessboard board is a board where no 0's and no 1's are 4-di... | class Solution(object):
def movesToChessboard(self, board):
N = len(board)
ans = 0
# For each count of lines from {rows, columns}...
for count in (collections.Counter(map(tuple, board)), # get row
collections.Counter(zip(*board))): #get column
# If... | class Solution {
public int movesToChessboard(int[][] board) {
int N = board.length, colToMove = 0, rowToMove = 0, rowOneCnt = 0, colOneCnt = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (((board[0][0] ^ board[i][0]) ^ (board[i][j] ^ board[0][j])) == ... | class Solution {
const int inf = 1e9;
void transpose(vector<vector<int>>& board) {
const int n = board.size();
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
swap(board[i][j], board[j][i]);
}
bool isSame(vector<int> &r1, vector<int>& r2) {
... | /**
* @param {number[][]} board
* @return {number}
*/
var movesToChessboard = function(board) {
const boardSize = board.length;
const boardSizeIsEven = boardSize % 2 === 0;
if(!canBeTransformed(board)) return -1;
// to convert to 010101
let rowSwap = 0;
let colSwap = 0;
// to convert t... | Transform to Chessboard |
There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.
To represent this tree, you are given an integer array nums and a 2D array edges. Each nums... | class Solution:
def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]:
gcdset = [set() for i in range(51)]
for i in range(1,51):
for j in range(1,51):
if math.gcd(i,j) == 1:
gcdset[i].add(j)
gcdset[j].... | class Solution {
//made TreeNode class for simple implementation in recurring function
class TreeNode{
int id;
int val;
List<TreeNode> child;
public TreeNode(int id,int val){
this.id=id;this.val=val;child=new ArrayList<>();
}
}
public int[] getCoprimes... | class Solution {
public:
vector<int> adj[100009];
vector<int> d[55];
int dis[100009];
void dfs(vector<int>& nums,vector<int> &ans,int i,int p,int h1)
{
int h=nums[i];
dis[i]=h1;
ans[i]=-1;
int val=-1;
for(int w=1;w<=50;w++)
{
if(__gcd(h,w)=... | var getCoprimes = function(nums, edges) {
const node = {}
const ans = Array(nums.length).fill(null)
function addNode(f, t){
if(!node[f]){
node[f]=[]
}
node[f].push(t)
}
edges.forEach(([f, t])=>{
addNode(f, t)
addNode(t, f)
})
... | Tree of Coprimes |
You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type.
You need to distribute all products to the retail stores follo... | class Solution:
def minimizedMaximum(self, n: int, quantities: List[int]) -> int:
def cond(m, n):
return sum([(q // m) + (q % m > 0) for q in quantities]) <= n
l, r = 1, max(quantities)
while l < r:
m = (l + r) // 2
if cond(m, n):
... | class Solution {
public int minimizedMaximum(int n, int[] quantities) {
int lo = 1;
int hi = (int)1e5;
int ans = -1;
while(lo <= hi){
int mid = (lo + hi)/2;
if(isItPossible(mid, quantities, n)){
... | class Solution {
public:
bool func(int N, int n, vector<int>& quantities){
int temp = 0;
for(int id = 0; temp <= n && id != quantities.size(); id++)
temp += quantities[id] / N + (quantities[id] % N ? 1 : 0);
return temp <= n;
}
int minimizedMaximum(int n, vector<int>& quantities) {
i... | var minimizedMaximum = function(n, quantities) {
const MAX = Number.MAX_SAFE_INTEGER;
const m = quantities.length;
let left = 1;
let right = quantities.reduce((acc, num) => acc + num, 0);
let minRes = MAX;
while (left <= right) {
const mid = (left + right) >> 1;
if (canDistri... | Minimized Maximum of Products Distributed to Any Store |
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Implement the Solution class:
Solution(ListNode head) Initializes the object with the head of the singly-linked list head.
int getRandom() Chooses a node randomly from the list a... | class Solution:
def __init__(self, head: Optional[ListNode]):
self.lst = []
while head:
self.lst.append(head.val)
head = head.next
def getRandom(self) -> int:
return random.choice(self.lst) | class Solution {
int N = 0;
ListNode head = null;
public Solution(ListNode head) {
this.head = head;
}
public int getRandom() {
ListNode p = this.head;
int i = 1, ans = 0;
while (p != null) {
if (Math.random() * i < 1) ans = p.val; // replace ans with... | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<int>v;
Solution(ListNode* head... | var Solution = function(head) {
this.res = [];
let curr = head;
while(curr !== null) {
this.res.push(curr)
curr = curr.next;
}
this.length = this.res.length;
};
Solution.prototype.getRandom = function() {
//Math.random() will generate a random number... | Linked List Random Node |
Given a list of words, list of single letters (might be repeating) and score of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).
It is not necessary to use all characters in letters and each let... | from itertools import combinations
class Solution:
def createNewWord(self, wordList) :
ans = ''
for word in wordList :
ans += word
charList = [i for i in ans]
return charList
def maxScoreWords(self, words: List[str], letters: List[str], score: List[... | class Solution {
int[] memo;
public int maxScoreWords(String[] words, char[] letters, int[] score) {
memo = new int[words.length];
Arrays.fill(memo,-1);
HashMap<Character,Integer> hm = new HashMap<>();
for(char c : letters){
int t = hm.getOrDefault(c,0);
t... | class Solution {
public:
int calc(vector<string>& words,map<char,int>&m,vector<int>& score,int i){
int maxi=0;
if(i==words.size())
return 0;
map<char,int>m1=m;//Creating a duplicate in case the given word does not satisfy our answer
int c=0;//Store the score
for(... | var maxScoreWords = function(words, letters, score) {
// unique chars
let set = new Set();
for (let w of words)
for (let c of w)
set.add(c)
// score of unique chars
let map = new Map();
for (let c of set)
map.set(c, score[c.charCodeAt() - 'a'.charCodeAt()])
// l... | Maximum Score Words Formed by Letters |
You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result... | class Solution:
def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:
hash_map = {s[0]: 1}
x = hash_map
prefix = [hash_map]
for i in range(1, len(s)):
x = x.copy()
x[s[i]] = x.get(s[i], 0) + 1
prefix.append(x)
... | class Solution
{
public List<Boolean> canMakePaliQueries(String s, int[][] queries)
{
List<Boolean> list = new ArrayList<>();
int n = s.length();
int[][] map = new int[n+1][26];
for(int i=0;i<s.length();i++)
{
for(int j=0;j<26;j++)
... | class Solution {
public:
vector<bool> canMakePaliQueries(string s, vector<vector<int>>& queries) {
vector<vector<int>>table(s.size(), vector<int>(26,0));
vector<bool>ans;
table[0][s[0]-'a']++;
for(int i = 1; i != s.size(); i++){
for(int j = 0; j != 26; j++) table[i][j] = table[i-1][j];
ta... | const getBitCount = (n) => {
let cnt = 0;
while(n > 0) {
cnt += n & 1;
n >>= 1;
}
return cnt;
}
var canMakePaliQueries = function(s, queries) {
const masks = [0], base = 'a'.charCodeAt(0);
let mask = 0;
for(let c of s) {
mask ^= (1 << (c.charCodeAt(0) - base));
... | Can Make Palindrome from Substring |
You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:
subtexti is a non-empty string.
The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text).
subtexti == subtextk - i + 1 for all valid values of i (i.e.... | class Solution:
def longestDecomposition(self, text: str) -> int:
left, right = 0, len(text) - 1
sol, last_left = 0, 0
a, b = deque(), deque()
while right > left:
a.append(text[left])
b.appendleft(text[right])
if a == b:
sol += 2
... | class Solution {
public int longestDecomposition(String text) {
int n = text.length();
for (int i = 0; i < n/2; i++)
if (text.substring(0, i + 1).equals(text.substring(n-1-i, n)))
return 2+longestDecomposition(text.substring(i+1, n-1-i));
return (n==0)?0:1;
}
} | class Solution {
public:
int longestDecomposition(string text) {
if(text.size() == 0)
return 0;
int i = 0;
deque<char> sFront;
deque<char> sBack;
while(i < text.size() / 2){
sFront.push_back(text[i]);
sBack.push_front(text[text.size() - 1 -... | var longestDecomposition = function(text) {
var i = 1
var output = 0
while(i < text.length)
{
if(text.substring(0,i) == text.substring(text.length-i))
{
output += 2 //add 2 to simulate adding to both sides of output array
text = text.substring(i,text.length-i) //c... | Longest Chunked Palindrome Decomposition |
You are given the root of a binary tree containing digits from 0 to 9 only.
Each root-to-leaf path in the tree represents a number.
For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit... | # 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 sumNumbers(self, root: Optional[TreeNode]) -> int:
int_list = []
def t... | class Solution {
int res;
public int sumNumbers(TreeNode root) {
res = 0;
getSum(root, 0);
return res;
}
public void getSum(TreeNode root, int sum){
if(root.left == null && root.right == null) {
res += (sum*10+root.val);
}
... | class Solution {
public:
int ans=0;
void dfs(TreeNode* root, string s){
if(!root->left && !root->right){
s+=to_string(root->val);
ans+=stoi(s);
return;
}
string o = s;
s+=to_string(root->val);
if(root->left) dfs(root->left,s);
i... | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumNumbers = func... | Sum Root to Leaf Numbers |
Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Ex... | from sortedcontainers import SortedList
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
sl = SortedList()
for i in range(len(nums)):
if i > k: sl.remove(nums[i-k-1])
idxl = sl.bisect_left(nums[i]-t)
idxr = sl.bisect_right(nums[i]+t)
... | /**
* Sliding Window solution using Buckets
*
* Time Complexity: O(N)
*
* Space Complexity: O(min(N, K+1))
*
* N = Length of input array. K = Input difference between indexes.
*/
class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (nums == null || nums.length... | class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
int i=0;
map<int,int> mp;
int n=nums.size();
for(int j=0;j<n;j++){
auto val=mp.lower_bound(nums[j]);
if(val!=mp.end() and (val->first-nums[j])<=value... | /**
* @param {number[]} nums
* @param {number} k
* @param {number} t
* @return {boolean}
*/
var containsNearbyAlmostDuplicate = function(nums, k, t) {
for(let i=0;i<nums.length;i++){
for(let j=i+1;j<nums.length;j++){
if(Math.abs(nums[i]-nums[j])<=t && (Math.abs(i-j)<=k)){
ret... | Contains Duplicate III |
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.
Example 1:
Input: nums = [3,1,2,2,2,1,3], k = 2
Output: 4
Explanation:
There are 4 pairs that meet all the requirements:... | class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
n=len(nums)
c=0
for i in range(0,n):
for j in range(i+1,n):
if nums[i]==nums[j] and ((i*j)%k==0):
c+=1
return c | class Solution {
public int countPairs(int[] nums, int k) {
HashMap<Integer,List<Integer>> hMap = new HashMap<>();
int count = 0;
for(int i = 0 ; i < nums.length ; i++){
if(!hMap.containsKey(nums[i])){
List<Integer> l = new ArrayList<>();
l.add(i);
... | class Solution {
public:
int countPairs(vector<int>& nums, int k) {
int count=0;
for(int i=0;i<nums.size()-1;i++)
{
for(int j=i+1;j<nums.size();j++)
if(nums[i]==nums[j] && i*j%k==0)
{
count++;
}
}
... | /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var countPairs = function(nums, k) {
var count = 0;
for(let i=0; i<nums.length; i++){
for(let j=i+1; j<nums.length; j++){
if(nums[i] == nums[j] && (i * j) % k == 0){
count++;
}
}
... | Count Equal and Divisible Pairs in an Array |
Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4... | class Solution:
def minimumTotal(self, t: List[List[int]]) -> int:
dp = []
dp.append(t[0])
r = len(t)
answer = float('inf')
for i in range(1, r):
c = len(t[i])
dp.append([])
for j in range(0, c):
if j == 0:
... | class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.get( triangle.size() - 1).size();
int dp[] = new int[n + 1];
for(int i = triangle.size() - 1; i>=0; i--)
{
for(int j = 0; j<triangle.get(i).size(); j++)
dp[j] = tri... | class Solution {
public:
int travel(vector<vector<int>>& tr , int lvl , int ind) {
if(ind >= tr[lvl].size()) // To check if we are going out of bound
return INT_MAX;
if(lvl == tr.size() - 1) { // Return if we are on last line
return tr[lvl][ind];
... | var minimumTotal = function(triangle) {
const memo = {};
function minPath(row, col) {
let key = `${row}:${col}`;
if (key in memo) {
return memo[key];
}
let path = triangle[row][col];
if (row < triangle.length - 1) {
... | Triangle |
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node ... | class Solution:
def bstToGst(self, root):
self.total = 0
def dfs(n):
if n:
dfs(n.right)
self.total += n.val
n.val = self.total
dfs(n.left)
dfs(root)
return root | class Solution {
int sum=0;
public TreeNode bstToGst(TreeNode root) {
if(root!=null){
bstToGst(root.right);
sum += root.val;
root.val = sum;
bstToGst(root.left);
}
return root;
}
} | class Solution {
public:
int s = 0;
void solve(TreeNode* root){
if(!root) return;
solve(root->right);
root->val = s + root->val;
s = root->val;
solve(root->left);
return;
}
TreeNode* bstToGst(TreeNode* root) {
if(!root) return NULL;
so... | var bstToGst = function(root) {
let sum = 0;
const traverse = (r = root) => {
if(!r) return null;
traverse(r.right);
let temp = r.val;
r.val += sum;
sum += temp;
traverse(r.left);
}
traverse();
return root;
}; | Binary Search Tree to Greater Sum Tree |
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.
Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion.
Implement the CBTInserter class:
CBTInserter(TreeNode ... | class CBTInserter:
def __init__(self, root: Optional[TreeNode]):
self.root = root
self.queue = Queue()
self.queue.put(self.root)
self.parent_of_last_inserted = None
def insert(self, val: int) -> int:
if self.parent_of_last_inserted is not None and self.parent_of... | class CBTInserter {
private TreeNode root;
private int total;
private int count(TreeNode root) {
if (root == null) return 0;
return 1+count(root.left)+count(root.right);
}
public CBTInserter(TreeNode root) {
this.root = root;
total = count(root);
}
private... | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) ... | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
*/
var CBTInserter = function(root) {
th... | Complete Binary Tree Inserter |
You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.
You are trying to write s across several lines, where each line is no longer than 100 pixels. ... | class Solution:
def numberOfLines(self, w: List[int], s: str) -> List[int]:
r=[0]*2
px=0
l=1
for i in range(len(s)):
px+=w[ord(s[i])-97]
if px>100:
l+=1
px=w[ord(s[i])-97]
print(ord(s[i]))
r[... | class Solution {
public int[] numberOfLines(int[] widths, String s) {
int sum=0,count=0;
for(int j=0;j<s.length();j++)
{
int pos = s.charAt(j)-'a';
sum+=widths[pos];
if(sum>100)
{
j--;
... | class Solution {
public:
vector<int> numberOfLines(vector<int>& widths, string s) {
vector<int>ans(2);
int lines =0;
int calc = 0;
int i =0;
while(i<s.length()){
calc = 0;
while(i<s.length() and calc<=100){
calc+=widths[s[i]-'a'];
... | var numberOfLines = function(widths, s) {
let pixel=100, line=1;
for(let i=0; i<s.length; i++){
if(pixel>=widths[s[i].charCodeAt()-97]){
pixel-=widths[s[i].charCodeAt()-97];
}else{
// this word should be written in NEXT line, so it CANNOT count.
i--; line++; p... | Number of Lines To Write String |
You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the pe... | class Solution:
def customSortString(self, order: str, s: str) -> str:
charValue = [0] * 26
for i in range(len(order)):
idx = ord(order[i]) - ord('a')
charValue[idx] = 26 - i
arrS = []
n = 0
for c in s:
arrS.append(c)
n += 1
... | class Solution {
public String customSortString(String order, String s) {
if(s.length() <= 1) return s;
StringBuilder finalString = new StringBuilder();
HashMap<Character, Integer> hm = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
char actualChar = s.charAt(i)... | class Solution {
public:
string customSortString(string order, string s) {
map<char,int>mp;
for(int i =0 ; i<order.size() ; i++)
mp[order[i]]=i+1;
vector<pair<int,char> > p;
int x=200;
for(int i =0 ; i < s.size(); i++)
{
if(mp[s[i]]!=0)
... | var customSortString = function(order, s) {
const hm = new Map();
for(let c of s) {
if(!hm.has(c)) hm.set(c, 0);
hm.set(c, hm.get(c) + 1);
}
let op = "";
for(let c of order) {
if(hm.has(c)) {
op += "".padStart(hm.get(c), c);
hm.delete(c);
... | Custom Sort String |
Given a string formula representing a chemical formula, return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than 1. If the count ... | from collections import Counter, deque
class Solution:
def countOfAtoms(self, formula: str) -> str:
"""
parser:
formula: elem {count} formula
elem: term | ( formula )
term: [A-Z](a-z)+
count: [0-9]+
"""
def parse_form... | class Solution {
public String countOfAtoms(String formula) {
Deque<Integer> multiplier = new ArrayDeque<>();
Map<String, Integer> map = new HashMap<>();
int lastValue = 1;
multiplier.push(1);
// Iterate from right to left
for (int i = formula.length() - 1... | class Solution {
public:
// helper functions
bool isUpper(char ch) {
return ch >= 65 && ch <= 90;
}
bool isLower(char ch) {
return ch >= 97 && ch <= 122;
}
bool isLetter(char ch) {
return isUpper(ch) || isLower(ch);
}
bool isNumber(char ch) {
return ch ... | var countOfAtoms = function(formula) {
function getElementCount(flatFormula) {
const reElementCount = /([A-Z][a-z]*)(\d*)/g;
let matches = flatFormula.matchAll(reElementCount);
let output = new Map();
for (let [match, element, count] of matches) {
count ... | Number of Atoms |
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Sinc... | class Solution:
def merge(self, A: List[List[int]]) -> List[List[int]]:
#sort array wrt its 0'th index
A.sort(key=lambda x:x[0])
i=0
while i<(len(A)-1):
if A[i][1]>=A[i+1][0]:
A[i][1]=max(A[i+1][1],A[i][1])
A.pop(i+1)
else:
... | class Solution {
public int[][] merge(int[][] intervals) {
// sort
// unknown size of ans = use ArrayList
// insert from back
// case 1 : Merging
// start of new interval is less that end of old interval
// new end = Math.max(new intervals end, old... | class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> res;
int i=0;
while(i<=intervals.size()-1){
int start=intervals[i][0];
int end=intervals[i][1];
while... | /**
* @param {number[][]} intervals
* @return {number[][]}
*/
var merge = function(intervals) {
// sorting the intervals array first is a general good first step
intervals.sort((a,b) => a[0] - b[0]);
const result = [];
// i am using the result array as a way to compare previous and next intervals
... | Merge Intervals |
You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string..
Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.
Example 1:
Input: s = "cba", k = 1
Output: "acb"
Explanation:
I... | class Solution:
def orderlyQueue(self, s: str, k: int) -> str:
if k>1:
s=list(c for c in s)
s.sort()
return ''.join(s)
s1=s
for i in range(len(s)):
s=s[1:]+s[0]
s1=min(s1,s)
return s1 | // Time O(n)
// Space O(n)
class Solution {
public String orderlyQueue(String s, int k) {
int n = s.length();
String ans = "";
if (k == 1){
s+=s; // add itself again
for (int i = 0; i < n; i++) if (ans.isEmpty() || s.substring(i, i+n).compareTo(ans) < 0){
... | class Solution {
public:
string orderlyQueue(string s, int k) {
if(k>1){
sort(s.begin(),s.end());
return s;
}
else{
string res=s;
for(int i=0;i<s.length();i++){
s=s.substr(1)+s.substr(0,1);
res=min(res,s);
}
return res;
}
... | /**
* @param {string} s
* @param {number} k
* @return {string}
*/
var orderlyQueue = function(s, k) {
// rotate the string one by one, and check which is lexographically smaller
if (k === 1) {
let temp = `${s}`;
let smallest = `${s}`;
let count = 0;
while (count < s.length) {
temp = temp.s... | Orderly Queue |
Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Example 1:
Input: n = 987
Output: "987"
Example 2:
Input: n = 1234
Output: "1.234"
Constraints:
0 <= n <= 231 - 1
| class Solution(object):
def thousandSeparator(self, n):
"""
:type n: int
:rtype: str
"""
n = str(n)
if len(n) <= 3:
return str(n)
result = ""
dot = '.'
index = 0
startPos = len(n) % 3
if startPos == 0:
... | class Solution {
public String thousandSeparator(int n) {
StringBuffer str = new StringBuffer(Integer.toString(n));
int index = str.length() - 3;
while(index >= 1){
str.insert(index , '.');
index = index - 3;
}
return str.toSt... | class Solution {
public:
string thousandSeparator(int n) {
string s="";
int a=0;
if(n==0)return "0";
while(n>0){
s+=char(n%10+48);
a++;
n/=10;
if(a==3&&n!=0)
{
a=0;
s+=".";
}
}
... | var thousandSeparator = function(n) {
let ans = "";
if(n >= 1000){
const arr = String(n).split('');
for(let i=0;i<arr.length;i++){
let temp = arr.length - i;
if(temp === 3 && arr.length > temp || temp === 6 && arr.length > temp || temp === 9 && arr.length > temp || temp === ... | Thousand Separator |
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.
Given an integer array rains where:
rains[i] >... | from bisect import bisect_left
class Solution:
def avoidFlood(self, rains):
full_lakes, dry_dates = {}, []
ans = [-1] * len(rains)
for date, rain_lake in enumerate(rains):
if rain_lake == 0: # no rain, we can dry one lake
dry_dates.append(date) # keep dry date... | class Solution {
public int[] avoidFlood(int[] rains) {
// the previous appeared idx of rains[i]
Map<Integer, Integer> map = new HashMap<>();
TreeSet<Integer> zeros = new TreeSet<>();
int[] res = new int[rains.length];
for (int i = 0; i < rains.length; i++) {
if (... | class Solution {
public:
vector<int> avoidFlood(vector<int>& rains) {
vector<int> ans(rains.size() , -1) ;
unordered_map<int,int> indices ; //store the lake and its index
set<int> st ; //stores the indices of zeros
for(int i = 0 ; i < rains.size() ; ++i ){
if(!... | var avoidFlood = function(rains) {
const n = rains.length;
const filledLakes = new Map();
const res = new Array(n).fill(-1);
const dryDays = [];
for (let i = 0; i < n; i++) {
const lake = rains[i]; // lake to rain on
if (lake === 0) {
// It is a dry day
dryDays.... | Avoid Flood in The City |
You are given a string s. You can convert s to a palindrome by adding characters in front of it.
Return the shortest palindrome you can find by performing this transformation.
Example 1:
Input: s = "aacecaaa"
Output: "aaacecaaa"
Example 2:
Input: s = "abcd"
Output: "dcbabcd"
Constraints:
0 <= s.l... | class Solution:
def shortestPalindrome(self, s: str) -> str:
end = 0
# if the string itself is a palindrome return it
if(s == s[::-1]):
return s
# Otherwise find the end index of the longest palindrome that starts
# from the first charac... | class Solution {
public String shortestPalindrome(String s) {
for(int i=s.length()-1; i >= 0; i--){
if(isPalindrome(s, 0, i)){
String toAppend = s.substring(i+1);
String result = new StringBuilder(toAppend).reverse().append(s).toString();
return re... | class Solution {
public:
string shortestPalindrome(string s) {
int BASE = 26, MOD = 1e9+7;
int start = s.size()-1;
// Calculate hash values from front and back
long front = 0, back = 0;
long power = 1;
for(int i=0; i<s.size(); i++){
... | var shortestPalindrome = function(s) {
const rev = s.split('').reverse().join('');
const slen = s.length;
const z = s + '$' + rev;
const zlen = z.length;
const lpt = new Array(zlen).fill(0);
for(let i = 1; i < zlen; i++) {
let j = lpt[i-1];
while(j > 0 && z.charAt(i) != z.cha... | Shortest Palindrome |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.