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 |
|---|---|---|---|---|---|
On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).
A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a... | class Solution:
def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
x_dir = [2, 1, -1, -2, -2, -1, 1, 2]
y_dir = [1, 2, 2, 1, -1, -2, -2, -1]
cache = {}
def kMoves(i, j, moves):
if i >= n or j >= n or i < 0 or j < 0:
... | class Solution {
public double knightProbability(int n, int k, int row, int column) {
double [][]curr=new double[n][n];
double [][]next=new double[n][n];
curr[row][column]=1;
int [][]dir={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
for(int p=1;... | class Solution {
public:
// declare a dp
double dp[30][30][105];
// x and y co-ordinates of 8 directions
vector<int> dx = {-2, -2, -1, 1, 2, 2, 1, -1};
vector<int> dy = {-1, 1, 2, 2, 1, -1, -2, -2};
double dfs(int i, int j, int n, int moves)
{
// base cas... | var knightProbability = function(n, k, row, column) {
if (k === 0) return 1;
const dirs = [[-2, -1], [-1, -2], [1, -2], [2, -1], [2, 1], [1, 2], [-1, 2], [-2, 1]];
const dp = Array(k + 1)
.fill('')
.map(_ => Array(n).fill('').map(_ => Array(n).fill(0)));
const isOut = (pos) => pos < 0 |... | Knight Probability in Chessboard |
You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.
Rearrange the spaces so that there is an equal number of spaces between every pair... | class Solution(object):
def reorderSpaces(self, text):
word_list = text.split()
words, spaces = len(word_list), text.count(" ")
if words > 1:
q, r = spaces//(words-1), spaces%(words-1)
return (" " * q).join(word_list) + " " * r
else:
retur... | class Solution {
public String reorderSpaces(String text) {
int spaces = 0;
//count the spacex
for(char c: text.toCharArray()){
if(c==' ')
spaces++;
}
//form word array
String[] words = text.trim().split("\\s+");
int nWords = word... | class Solution {
public:
string reorderSpaces(string text) {
int ct=0;
// Collection of words
vector<string> v;
for (int i=0; i<text.size(); i++){
// Calculate the numbert of spaces
while(i<text.size() && text[i] == ' '){
ct++;
... | var reorderSpaces = function(text) {
let arr = text.split(" ");
let totalSpace = arr.length-1;
arr = arr.filter(w => w !== '');
let spaceBetween = arr.length > 1 ?
Math.floor(totalSpace / (arr.length-1)) : 0;
let spaceLeftOver = arr.length > 1 ?
totalSpace % (... | Rearrange Spaces Between Words |
Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.
The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.
A valid square has four equal sides with positive length and four equal angles (90-degree angles).
 ... | class Solution:
def validSquare(self, p1, p2, p3, p4):
def cal(A, B):
return abs(A[0] - B[0]) + abs(A[1] - B[1])
d = [cal(p1, p2), cal(p1, p3), cal(p1, p4), cal(p2, p3), cal(p2, p4), cal(p3, p4)]
d.sort()
return 0 < d[0] == d[1] == d[2] == d[3] and d[4] == d[5] | class Solution {
// This method returns true if the given 4 points form a square, false otherwise
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
// We use a set to store the distances between the points
Set<Integer> set = new HashSet();
// Calculate the distances be... | class Solution {
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
vector<vector<int>> p{p1, p2, p3, p4};
unsigned short ans{0};
double scal;
vector<double> bar(2);
/* compute the barycenter */
bar[0] = (p1[0] + p2[0] + p3... | var validSquare = function(p1, p2, p3, p4) {
const distance = (a, b) => {
const [aX, aY] = a;
const [bX, bY] = b;
return (aX - bX) ** 2 + (aY - bY) ** 2;
};
const set = new Set([
distance(p1, p2),
distance(p1, p3),
distance(p1, p4),
distance(p2, p3),
... | Valid Square |
You are given a 0-indexed integer array nums. The array nums is beautiful if:
nums.length is even.
nums[i] != nums[i + 1] for all i % 2 == 0.
Note that an empty array is considered beautiful.
You can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted... | class Solution:
def minDeletion(self, nums: List[int]) -> int:
# Greedy !
# we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0
# at the begining, we consider the num on the even index
# when we delete a num, we need consider the num on the odd index
... | class Solution {
public int minDeletion(int[] nums) {
int deletion = 0, n = nums.length;
for (int i=0; i<n-1; ) {
int newIndex = i-deletion;
if ((newIndex % 2 == 0) && nums[i] == nums[i+1]) deletion++;
else i++;
}
return ((n-deletion) % 2 == 0) ?... | INTUITION
1. since we have to find the minimum deletions, we dont have to
actually delete the elements , we just have to count those elements.
2. Now if we delete the element and shift all the elements towards left , it will
cause time limit exceeded.
3. To handle above case we can observe one thing that, if we del... | var minDeletion = function(nums) {
const n = nums.length;
const res = [];
for (let i = 0; i < n; ++i) {
const num = nums[i];
if (res.length % 2 === 0 || res.at(-1) != num) {
res.push(num);
}
}
if (res.length % 2 === 1) res.pop();
return n - res.length;
}; | Minimum Deletions to Make Array Beautiful |
Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise.
An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.
Example 1:
Input: nums =... | class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
psum = {0:-1}
currentSum = 0
for i in range(len(nums)):
currentSum += nums[i]
remainder = currentSum % k
if remainder not in psum:
psum[remainder] = i
... | class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
boolean t[]=new boolean[nums.length+1];
Arrays.fill(t,false);
return help(nums.length,nums,k,0,0,t);
}
public boolean help(int i,int nums[],int k,int sum,int size,boolean t[]){
if(size>=2&&sum%k==0){
... | class Solution {
public:
bool checkSubarraySum(vector<int>& nums, int k) {
unordered_set<int> s;
int sum = 0;
int pre = 0;
for(int i = 0; i < nums.size(); i++)
{
sum += nums[i];
int remainder = sum%k;
if (s.find(remainder) != s.end())
... | var checkSubarraySum = function(nums, k) {
const hash = new Map([[0, -1]]);
let sum = 0;
for (let index = 0; index < nums.length; index++) {
sum += nums[index];
const r = sum % k;
if (hash.has(r)) {
if (index - hash.get(r) > 1) return true;
}
else hash.set(r, index);
}
return false;
}; | Continuous Subarray Sum |
You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid iti... | class Solution:
def findTicketsAdjList(self, tickets):
ticket = {}
for src,dest in tickets:
if src in ticket:
ticket[src].append(dest)
else:
ticket[src] = [dest]
for src,dest in ticket.items():
if len(dest)>1:
... | class Solution {
LinkedList<String> res = new LinkedList<>();
public List<String> findItinerary(List<List<String>> tickets) {
HashMap<String,PriorityQueue<String>> map= new HashMap<>();
for(int i=0;i<tickets.size();i++){
String a=tickets.get(i).get(0);
String b=tickets.g... | class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, multiset<string>> myMap;
stack<string> myStack;
vector<string> ans;
for (int i=0; i<tickets.size(); ++i) {
myMap[tickets[i][0]].insert(tickets[i][1]);
}
... | function dfs(edges,s=`JFK`,ans=[`JFK`]){ //run dfs, starting node being `JFK`
if(!edges[s] || edges[s].length==0){ //if currenctly reached node has its adjacent list empty
let isAllTravelled=1;
Object.values(edges).forEach(ele=> {if(ele.length>0) isAllTravelled=0}) // check if every edge has been ... | Reconstruct Itinerary |
Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals.
Implement the SummaryRanges class:
SummaryRanges() Initializes the object with an empty stream.
void addNum(int val) Adds the integer val to the stream.
int[][] getIntervals() Ret... | class SummaryRanges:
def __init__(self):
self.intervals = []
def addNum(self, val: int) -> None:
left, right = 0, len(self.intervals) - 1
while left <= right:
mid = (left + right) // 2
e = self.intervals[mid]
if e[0] <= val <= e[1]: return
... | class SummaryRanges {
Map<Integer, int[]> st;
Map<Integer, int[]> end;
Set<Integer> pending;
int[][] prev = new int[0][];
Set<Integer> seen = new HashSet<>();
int INVALID = -1;
public SummaryRanges() {
st = new HashMap<>();
end= new HashMap<>();
pending = new HashSet... | class SummaryRanges {
public:
struct DSU {
map<int, int>parent;
map<int, int>sz;
int find_parent(int a) {
if(!parent.count(a)) {
parent[a] = a;
sz[a] = 1;
}
if(parent[a] == a) return a;
return parent[a] = find... | var SummaryRanges = function() {
this.tree = null // { val, left?, right? }
};
/**
* @param {number} val
* @return {void}
*/
SummaryRanges.prototype.addNum = function(val) {
if (!this.tree) {
this.tree = { val }
} else {
let node = this.tree
let parent, side
while (node)... | Data Stream as Disjoint Intervals |
There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).
You are also given a 0-indexed string s of length m whe... | class Solution:
def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
result = []
for idx in range(len(s)):
count, row, col = 0, startPos[0],startPos[1]
while idx < len(s):
if s[idx] == 'D':
row += 1
... | class Solution {
public int[] executeInstructions(int n, int[] startPos, String s) {
//Make array of length equal to string length
int ans[]=new int[s.length()];
//Now use two for loops
for(int i=0;i<s.length();i++){
//countmoves will keep on counting the valid moves fro... | class Solution {
public:
vector<int> executeInstructions(int n, vector<int>& start, string s) {
int m=s.size();
vector<int> ans(m);
for(int l=0;l<m;l++){
int count=0;
int i=start[0],j=start[1];
for(int k=l;k<m;k++){
if(s[k]=='L'){
if(j-1>=0){
j--;
count++;
}
else break;
... | // Time: O(n^2)
var executeInstructions = function(n, startPos, s) {
let answers = [];
for (i = 0; i < s.length; i++) {
let movement = 0;
let [row, col] = startPos;
for (j = i; j < s.length; j++) {
if (s[j] == "R") col++;
else if (s[j] == "L") col--;
e... | Execution of All Suffix Instructions Staying in a Grid |
Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vert... | class Solution:
def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:
def find(v, parent):
if parent[v] != v:
parent[v] = find(parent[v], parent)
return parent[v]
def union(u,v, parent):
parent[find(u,pare... | class Solution {
static class UnionFind{
int[]parent;
int[]rank;
int comp = 0;
UnionFind(int n){
parent = new int[n];
rank = new int[n];
comp = n;
for(int i=0;i<n;i++){
parent[i] = i;
rank[i] = 0;
... | class UnionFind{
private:
vector<int> parent_;
vector<int> rank_;
int sets_;
public:
UnionFind(int n)
{
init(n);
}
void init(int n)
{
sets_ = n;
parent_.resize(n);
rank_.resize(n);
iota(parent_.begin(),parent_.end(),0);
fill(rank_.begin(),r... | /**
* @param {number} n
* @param {number[][]} edges
* @return {number[][]}
*/
var findCriticalAndPseudoCriticalEdges = function(n, edges) {
// find and union utils
const find = (x, parent) => {
if (parent[x] === -1) { return x }
const y = find(parent[x], parent)
parent[x] = y
re... | Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree |
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Example 1:
Input: nums = [1... | class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
if len(nums) < 4: return []
nums.sort()
res = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
l = j+1
r = len(num... | class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> llans = new LinkedList<>();
if(nums == null || nums.length <= 2){
return llans;
}
for(int i=0;i<nums.length-3;i++){
for(int j=i+1;j<num... | class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
vector<vector<int> > answer;
if(n<4) return answer;
sort(nums.begin(),nums.end());
for(int i=0;i<n;){
for(int j=i+1;j<n;){
int left = j... | var fourSum = function(nums, target) {
nums.sort((a, b) => a - b);
const res = [];
for(let i=0; i<nums.length-3; i++) {
for(let j=i+1; j<nums.length-2; j++) {
let min = j + 1;
let max = nums.length - 1;
while(min < max) {
const sum = nums[i] +... | 4Sum |
You are given an array of points in the X-Y plane points where points[i] = [xi, yi].
Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.
Example 1:
Input: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]
Output: 4
Ex... | class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
points = sorted(points, key=lambda item: (item[0], item[1]))
cols = defaultdict(list)
for x,y in points:
cols[x].append(y)
lastx = {}
ans = float('inf')
for x... | class Solution {
public int minAreaRect(int[][] points) {
Map<Integer, Set<Integer>> map = new HashMap<>();
// Group the points by x coordinates
for (int[] point : points) {
if (!map.containsKey(point[0])) map.put(point[0], new HashSet<>());
map.get(point[0]).add(point[1... | class Solution {
public:
int minAreaRect(vector<vector<int>>& points) {
unordered_map<int, unordered_set<int>> pts;
for(auto p : points)
{
pts[p[0]].insert(p[1]);
}
int minArea = INT_MAX;
int n = points.size();
for(int i=0; i<n; i++)
... | var minAreaRect = function(points) {
const mapOfPoints = new Map();
let minArea = Infinity;
for(const [x,y] of points) {
let keyString = `${x}:${y}`
mapOfPoints.set(keyString, [x, y]);
}
for(const [xLeftBottom, yLeftBottom] of points) {
for(const [xRightTop, yRightTop] of poi... | Minimum Area Rectangle |
Given an array of integers nums, half of the integers in nums are odd, and the other half are even.
Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.
Return any answer array that satisfies this condition.
Example 1:
Input: nums = [4,2,5,7]
Output: [4,5,2,7]
Ex... | class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
arr = [None]*len(nums)
even,odd = 0,1
for i in(nums):
if i % 2 == 0:
arr[even] = i
even +=2
for i in (nums):
if i % 2 != 0:
arr[odd] = ... | class Solution {
public int[] sortArrayByParityII(int[] nums) {
int[] ans = new int[nums.length];
int even_pointer = 0;
int odd_pointer = 1;
for(int i = 0; i < nums.length; i++){
if(nums[i] % 2 == 0){
ans[even_pointe... | class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& nums) {
vector<int>ans(nums.size());
int even_idx=0;
int odd_idx=1;
for(int i=0;i<nums.size();i++)
{
if((nums[i]%2)==0) //the num is even
{
ans[even_idx]=nums[i];
... | var sortArrayByParityII = function(nums) {
let arrEven = []
let arrOdd = []
let result = []
for(let i in nums){
nums[i]%2==0 ? arrEven.push(nums[i]) : arrOdd.push(nums[i])
}
for(let i in arrEven){
result.push(arrEven[i])
result.push(arrOdd[i])
}
return result
}; | Sort Array By Parity II |
Write a program to count the number of days between two dates.
The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
Example 1:
Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1
Example 2:
Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15
Con... | from datetime import date
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
return abs((date.fromisoformat(date2) - date.fromisoformat(date1)).days) | class Solution {
public int daysBetweenDates(String date1, String date2) {
String[] d1 = date1.split("-");
String[] d2 = date2.split("-");
return (int)Math.abs(
daysFrom1971(Integer.parseInt(d1[0]), Integer.parseInt(d1[1]), Integer.parseInt(d1[2]))
- daysFrom1971(Inte... | class Solution
{
public:
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool isLeap(int y)
{
return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
}
int calc(string s)
{
int y = stoi(s.substr(0, 4));
int m = stoi(s.substr(5, 2));
int d = stoi(s.... | var daysBetweenDates = function(date1, date2) {
let miliSecondInaDay = 24*60*60*1000;
if(date1>date2) return (new Date(date1) - new Date(date2)) / miliSecondInaDay
else return (new Date(date2) - new Date(date1)) / miliSecondInaDay
}; | Number of Days Between Two Dates |
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
Example 1:
Input: a = 2, b = [3]
Output: 8
Example 2:
Input: a = 2, b = [1,0]
Output: 1024
Example 3:
Input: a = 1, b = [4,3,3,8,5,2]
Output: 1
Constrai... | class Solution:
def superPow(self, a: int, b: List[int]) -> int:
mod = 1337
ans = 1
for power in b:
ans = ((pow(ans,10)%mod)*(pow(a,power)%mod))%mod
return ans | import java.math.BigInteger;
class Solution {
public int superPow(int a, int[] b) {
StringBuilder bigNum = new StringBuilder();
Arrays.stream(b).forEach(i -> bigNum.append(i));
return
BigInteger.valueOf(a)
.modPow(new BigInteger(bigNum.toString()), BigIntege... | class Solution {
public:
int binaryExp(int a, int b, int M)
{
int ans = 1;
a %= M;
while(b)
{
if(b&1) ans = (ans * a)%M;
a = (a*a)%M, b = b>>1;
}
return ans;
}
int superPow(int a, vector<int>& b) {
int bmod = 0;
... | var superPow = function(a, b) {
const MOD = 1337;
const pow = (num, n) => {
let result = 1;
for (let index = 0; index < n; index++) {
result = result * num % MOD;
}
return result;
};
return b.reduceRight((result, n) => {
a %= MOD;
const powNum... | Super Pow |
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.
It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.
A binary search tree is a binary t... | class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
if not preorder:
return None
node = preorder.pop(0)
root = TreeNode(node)
l = []
r = []
for val in preorder:
if val < node:
l.append(val)
else:
r.append(val)
root.left = self.bstFromPreorder(l)
root... | class Solution {
public TreeNode bstFromPreorder(int[] preorder) {
return bst(preorder, 0, preorder.length-1);
}
public TreeNode bst(int[] preorder, int start, int end){
if(start > end) return null;
TreeNode root = new TreeNode(preorder[start]);
int breakPoint = start+1;
... | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), l... | var bstFromPreorder = function(preorder) {
let head = new TreeNode(preorder[0]);
for (let i = 1, curr; i<preorder.length; i++) {
curr = head;
while (1) {
if (preorder[i]>curr.val)
if (curr.right !=null) { curr = curr.right; }
else { curr.right = new TreeNode(preorder[i]); brea... | Construct Binary Search Tree from Preorder Traversal |
Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
A palindrome string is a string that reads the same backward as forward.
Example 1:
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Example 2:
Input: s = "a"
Output: [... | """
we can approach this problem using manacher's algorithm with backtracking and recursion
"""
class Solution:
def partition(self, s: str) -> List[List[str]]:
lookup = {"": [[]]}
def lps(s):
if s in lookup:
return lookup[s]
final_res = []
result_... | // Plaindrome Partitioning
// Leetcode : https://leetcode.com/problems/palindrome-partitioning/
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
if(s == null || s.length() == 0)
return result;
helper(s, 0, new ArrayL... | class Solution {
public:
bool check(string k)
{
string l=k;
reverse(l.begin(),l.end());
if(k==l)return true;
return false;
}
void solve(string &s,vector<vector<string>>&ans,
vector<string>temp,int pos)
{
if(pos>=s.size()){ans.push_back(temp); re... | var partition = function(s) {
let result = []
backtrack(0, [], s, result)
return result
};
function backtrack(i, partition, s, result){
if(i === s.length){
result.push([...partition])
return
}
for(let j=i;j<s.length;j++){
let str = s.slice(i,j+1)
if(isPal(str)){... | Palindrome Partitioning |
Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
Example 1:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Example 2:
Input: arr = [1,1]
Output: 1
Constraints:
1 <= arr.length <= 104
0... | class Solution:
def findSpecialInteger(self, arr: List[int]) -> int:
l=len(arr)
c=(l//4)+1
d={}
for i in arr:
if i in d:
d[i]+=1
else:
d[i]=1
if d[i]>=c:
return i | class Solution {
public int findSpecialInteger(int[] arr) {
if (arr.length == 1) {
return arr[0];
}
int count = (int) Math.ceil(arr.length / 4);
System.out.println(count);
Map<Integer, Integer> map = new HashMap<>();
for (Integer i : arr) {
... | class Solution {
public:
int findSpecialInteger(vector<int>& arr) {
int freq = 0.25 * arr.size();
map<int,int>m;
for(int i: arr)
m[i]++;
int k;
for(auto i: m)
{
if(i.second > freq)
{
k = i.first;
... | function binarySearch(array, target, findFirst) {
function helper(start, end) {
if (start > end) {
return -1;
}
const middle = Math.floor((start + end) / 2);
const value = array[middle];
if (value === target) {
if (findFirst) {... | Element Appearing More Than 25% In Sorted Array |
You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
A board that redirects the ball to the right spans the top-left co... | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m,n=len(grid),len(grid[0])
for i in range(m):
grid[i].insert(0,1)
grid[i].append(-1)
res=[]
for k in range(1,n+1):
i , j = 0 , k
struck = False
while ... | class Solution {
public int dfs(int[][] grid, int i, int j){
if(i==grid.length)
return j;
if(j<0 || j>=grid[0].length)
return -1;
if(grid[i][j]==1 && j+1<grid[0].length && grid[i][j+1]==1)
return dfs(grid,i+1,j+1);
else if(grid[i][j]==-1 && j-1>... | class Solution {
public:
int util(vector<vector<int>>&grid,bool top,int i,int j)
{
if(top==0&&i==grid.size()-1)return j;
if(top==1)
{
if(grid[i][j]==1)
{
if(j+1>=grid[0].size()||grid[i][j+1]==-1)return -1;
return util(grid,!top,i,j+... | var findBall = function(grid) {
let m = grid.length,
n = grid[0].length,
ans = []
for (let start = 0; start < n; start++) { // Iterate through the different starting conditions
let j = start
for (let i = 0; i < m; i++) { // Then iterate downward from grid[i][j]
... | Where Will the Ball Fall |
You are given an integer array nums and an integer k.
In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.
Return the maximum number of operations you can perform on the array.
Example 1:
Input: nums = [1,2,3,4], k = 5
Output: 2
Explanation: Starting wi... | class Solution:
def maxOperations(self, nums: List[int], k: int) -> int:
nums.sort()
left = 0
right = len(nums) - 1
ans = 0
while left < right:
cur = nums[left] + nums[right]
if cur == k:
ans += 1
left += 1
... | class Solution {
public int maxOperations(int[] nums, int k) {
HashMap<Integer,Integer>map=new HashMap<>();
int count=0;
for(int i=0;i<nums.length;i++){
//to check if that k-nums[i] present and had some value left or already paired
if(map.containsKey(k-nums[i])&&map.g... | class Solution {
public:
int maxOperations(vector<int>& nums, int k) {
unordered_map<int, int> Map;
for (auto &num: nums) Map[num]++; // count freq of nums
int ans = 0;
for(auto it=Map.begin(); it!=Map.end(); ++it){
int num = it->first, count = it->second;
if(k - num == n... | var maxOperations = function(nums, k) {
let freq = new Map(),count=0;
for (let i = 0; i < nums.length; i++) {
if (freq.get(k-nums[i])) {
if(freq.get(k-nums[i])==1) freq.delete(k-nums[i])
else freq.set(k-nums[i],freq.get(k-nums[i])-1)
count++;
}else freq.set(nums[i],freq.get(nums[i])+1||... | Max Number of K-Sum Pairs |
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the coo... | class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
cont = 0
c = 0
k = 0
while k< len(s) and c < len(g):
if s[k] >= g[c]:
c+=1
k+=1
cont+=1
else:
... | class Solution {
public int findContentChildren(int[] g, int[] s) {
int i =0,j=0,c=0;
Arrays.sort(g);
Arrays.sort(s);
for(;i< g.length;i++)
{
// System.out.println(s[j]+" "+g[i]);
while(j<s.length)
{
... | class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
int n=g.size();
int m=s.size();
if(n==0 or m==0)return 0;
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int i=0,j=0;
while(i<m and j<n)
{
if(s[i]>=g[j])
... | var findContentChildren = function(g, s) {
g.sort(function(a, b) {
return b - a;
});
s.sort(function(a, b) {
return a - b;
});
let content = 0;
for (let curG of g) {
for (let curS of s) {
if (curS >= curG) {
s.pop();
content++;
break;
}
... | Assign Cookies |
Balanced strings are those that have an equal quantity of 'L' and 'R' characters.
Given a balanced string s, split it into some number of substrings such that:
Each substring is balanced.
Return the maximum number of balanced strings you can obtain.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanatio... | class Solution:
def balancedStringSplit(self, s: str) -> int:
r_count=l_count=t_count=0
for i in s:
if i=='R':
r_count+=1
elif i=='L':
l_count+=1
if r_count==l_count:
t_count+=1
r_count=0
... | class Solution {
public int balancedStringSplit(String s) {
int nl = 0;
int nr = 0;
int count = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.substring(i,i+1).equals("L")) ++nl;
else ++nr;
if (nr == nl) {
++count;
}
... | class Solution {
public:
int balancedStringSplit(string s) {
int left = 0;
int right = 0;
int cnt = 0;
for(int i=0 ; i<s.size() ; i++){
if(s[i] == 'L'){
left++;
}
if(s[i] == 'R'){
right++;
}
if(left - right == 0){
cnt++;
}
}
return cnt;
}
} | var balancedStringSplit = function(s) {
let r_count = 0;
let l_count = 0;
let ans =0;
for(let i = 0 ; i < s.length;i++){
if(s[i]==='R') r_count++;
else l_count++;
if(l_count==r_count) {
l_count=0
r_count=0;
ans++
}
}
return ans
}; | Split a String in Balanced Strings |
You are given a 2D integer array groups of length n. You are also given an integer array nums.
You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the s... | class Solution:
def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:
groups = ['-'.join(str(s) for s in group) for group in groups]
nums = '-'.join(str(s) for s in nums)
j = k = 0
while k < len(groups):
group = groups[k]
i = nums.find(group, ... | class Solution {
public int search(int[] group, int[] nums, int start, int end )
{
int i=start, j=0;
while(i<end && j<group.length)
{
if(nums[i] == group[j])
{
i++;
j++;
if(j == group.length)
... | class Solution {
public:
//Idea is to use KMP Longest Prefix Suffix array to match if one array is subarray of another array.
bool canChoose(vector<vector<int>>& groups, vector<int>& nums) {
int m = nums.size();
int index = 0;
for(auto group : groups){
int n = group.size();
... | /**
* @param {number[][]} groups
* @param {number[]} nums
* @return {boolean}
*/
var canChoose = function(groups, nums) {
let i=0;
for(let start=0;i<groups.length&&groups[i].length+start<=nums.length;start++){
if(search(groups[i], nums, start)){
start+=groups[i].length-1;
... | Form Array by Concatenating Subarrays of Another Array |
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u, v) which consists of one element from the first array and one element from the second array.
Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.
Example 1:
Input: nums1 = [1... | import heapq
class Solution:
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
ans = []
heapq.heapify(ans)
for i in range(min(k,len(nums1))):
for j in range(min(k,len(nums2))):
pairs = [nums1[i],nums2[j]]
i... | class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<int []> pq = new PriorityQueue<>(
(a, b) -> (a[0] + a[1]) - (b[0] + b[1])
);
for(int i = 0; i < nums1.length && i < k; i++){
pq.add(new int[]{nums1[i], nums2[0]... | class Solution {
public:
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
priority_queue<pair<int,pair<int,int>>> pq;
int m=nums1.size(),n=nums2.size();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int sum=nums1[i]+nums2[j];
... | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k
* @return {number[][]}
*/
var kSmallestPairs = function(nums1, nums2, k) {
const h = new MinHeap();
h.sortKey = 'id';
for(i =0; i<nums1.length; i++)
h.push({id: nums1[i]+nums2[0], i: i, j: 0});
let res = [];
wh... | Find K Pairs with Smallest Sums |
Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
Example 1:
Input: root = [1,null,0,0,1]
Output: [1,null,0,null,1]
Explanation:
Only the red nodes s... | # 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 pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(node):
... | class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root == null) return root;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if(root.left == null && root.right == null && root.val == 0) return null;
else return root;
... | class Solution {
public:
TreeNode* pruneTree(TreeNode* root) {
if(!root) return NULL;
root->left = pruneTree(root->left);
root->right = pruneTree(root->right);
if(!root->left && !root->right && root->val==0) return NULL;
return root;
}
}; | /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var pruneTree = function(root) ... | Binary Tree Pruning |
A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign.
For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not.
You ar... | class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
s = sentence.split() # convert to List to easily update
m = discount / 100
for i,word in enumerate(s):
if word[0] == "$" and word[1:].isdigit(): # Check whether it is in correct format
... | class Solution {
public String discountPrices(String sentence, int discount) {
String x[] = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (String s : x) {
if (isPrice(s)) sb.append(calc(Double.parseDouble(s.substring(1)), discount) + " ");
else sb... | class Solution {
public:
string discountPrices(string sentence, int discount) {
// doit is a function
auto doit = [&](string word) {
int n(size(word));
if (word[0] != '$' or n == 1) return word;
long long price = 0;
for (int i=1; i... | var discountPrices = function(sentence, discount) {
let isNum = (num) => {
if(num.length <= 1 || num[0] != '$') return false;
for(let i = 1; i < num.length; ++i)
if(!(num[i] >= '0' && num[i] <= '9'))
return false;
return true;
};
let x = sentence.split(' '... | Apply Discount to Prices |
You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.
0 means the cell is empty, so you can pass through,
1 means the cell contains a cherry that you can pick up and pass through, or
-1 means the cell contains a thorn that blocks your way.
Return the maximum n... | class Solution:
def cherryPickup(self, grid):
n = len(grid)
dp = [[-1] * (n + 1) for _ in range(n + 1)]
dp[1][1] = grid[0][0]
for m in range(1, (n << 1) - 1):
for i in range(min(m, n - 1), max(-1, m - n), -1):
for p in range(i, max(-1, m - n), -1):
... | class Solution {
public int cherryPickup(int[][] grid) {
int m = grid.length, n = grid[0].length;
//For O(N^3) Dp sapce solution
dp2 = new Integer[m][n][m];
int ans=solve2(0,0,0,grid,0,m,n);
if(ans==Integer.MIN_VALUE) return 0;
return ans;
}
private Integ... | class Solution {
public:
int solve(int r1,int c1,int r2,vector<vector<int>>& grid, vector<vector<vector<int>>> &dp)
{
//Calculating c2 :
/*
(r1 + c1) = (r2 + c2)
c2 = (r1 + c1) - r2
*/
int c2 = (r1+c1)-r2 ;
//Base condition
if(r1 >= grid.si... | var cherryPickup = function(grid) {
let result = 0, N = grid.length, cache = {}, cherries;
const solve = (x1, y1, x2, y2) => {
if(x1 === N -1 && y1 === N-1)
return grid[x1][y1] !== -1 ? grid[x1][y1] : -Infinity;
if(x1 > N -1 || y1 > N-1 || x2 > N-1 || y2 > N-1 || grid[x1][y1] =... | Cherry Pickup |
Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] a... | class Solution:
def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
hash_map = {}
for i in range(0 , len(rounds)-1):
if i == 0:
start = rounds[i]
elif rounds[i] == n:
start = 1
else:
start = rounds[i] + 1
... | class Solution {
public List<Integer> mostVisited(int n, int[] rounds) {
int[]psum=new int[n+2];
psum[rounds[0]]+=1;
psum[rounds[1]+1]-=1;
if(rounds[0]>rounds[1])
psum[1]+=1;
for(int i=2;i<rounds.length;i++){
psum[rounds[i-1]+1]+=1;
psum[ro... | class Solution {
public:
vector<int> mostVisited(int n, vector<int>& rounds) {
vector <int> ans;
int size = rounds.size();
if(rounds[0] <= rounds[size-1]) {
for(int i=rounds[0]; i<= rounds[size-1]; i++) {
ans.push_back(i);
}
return... | var mostVisited = function(n, rounds) {
const first = rounds[0];
const last = rounds[rounds.length - 1];
const result = [];
if (first <= last) {
for (let i = last; i >= first; i--) result.unshift(i)
} else {
for (let i = 1; i <= last; i++) result.push(i);
for (let i =... | Most Visited Sector in a Circular Track |
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
... | class Solution:
def characterReplacement(self, s: str, k: int) -> int:
# Initialize variables
window_start = 0
max_length = 0
max_count = 0
char_count = {}
# Traverse the string s
for window_end in range(len(s)):
# Increment the count of the curre... | class Solution {
public int characterReplacement(String s, int k) {
HashMap<Character,Integer> map=new HashMap<>();
int i=-1;
int j=-1;
int ans=0;
while(true){
boolean f1=false;
boolean f2=false;
while(i<s.length()-1){
... | class Solution {
public:
int characterReplacement(string s, int k) {
int n = s.length();
if(n == k) return n;
if(n == 1) return 1;
int res = 0;
int maxCnt = 0;
unordered_map<char,int> mp;
for(int l = 0, r = 0; r < n; r++)
{
... | // O(n) time | O(26) -> O(1) space - only uppercase English letters
var characterReplacement = function(s, k) {
const sLen = s.length,
charCount = {};
if (k >= sLen) return sLen;
let maxLen = 0,
windowStart = 0,
maxRepeatChar = 0;
for (let windowEnd = 0; windowEnd < sLen; wind... | Longest Repeating Character Replacement |
You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.
Return all lonely numbers in nums. You may return the answer in any order.
Example 1:
Input: nums = [10,6,5,8]
Output: [10,8]
Explanation:
- 10 is a lonely ... | class Solution:
def findLonely(self, nums: List[int]) -> List[int]:
m = Counter(nums)
return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0] | class Solution {
public List<Integer> findLonely(int[] nums) {
Arrays.sort(nums);
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i < nums.length - 1; i++) {
if (nums[i - 1] + 1 < nums[i] && nums[i] + 1 < nums[i + 1]) {
list.add(nums[i]);
... | class Solution {
public:
vector<int> findLonely(vector<int>& nums) {
int n=nums.size();
unordered_map<int,int> ump;
vector<int> sol;
for(int i=0;i<n;i++)
{
ump[nums[i]]++;
}
for(auto a: ump)
{
if(a.second==1 and !ump.count(a.fir... | var findLonely = function(nums) {
let countMap = new Map();
let result = [];
for (let num of nums) {
countMap.set(num, (countMap.get(num) || 0) + 1);
}
for (let num of nums) {
if (!countMap.has(num - 1) && !countMap.has(num + 1) && countMap.get(num) === 1) {
result.push(... | Find All Lonely Numbers in the Array |
You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0").
Find the number of unique good subsequences of binary.
For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the unique good subs... | class Solution:
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
# zero_as_last: the count of S0, good sequence ending in 0
# one_as_last : the count of S1: good sequence ending in 1
# zero_exist: existence flag of 0 in given binary
dp = {"ze... | class Solution {
public int numberOfUniqueGoodSubsequences(String binary) {
int initialZeroCount= 0;
while(initialZeroCount < binary.length() && binary.charAt(initialZeroCount) == '0') initialZeroCount++;
if(initialZeroCount == binary.length()) return 1;
long[] dp = new long[binary.l... | class Solution {
int MOD = 1000000007;
public:
int numberOfUniqueGoodSubsequences(string binary) {
int zero = 0;
long long ones = 0;
long long zeros = 0;
for (int i = binary.size() - 1; i >= 0; --i) {
if (binary[i] == '1') {
ones = (ones + zer... | const MOD = 1000000007;
var numberOfUniqueGoodSubsequences = function(binary) {
let endsZero = 0;
let endsOne = 0;
let hasZero = 0;
for (let i = 0; i < binary.length; i++) {
if (binary[i] === '1') {
endsOne = (endsZero + endsOne + 1) % MOD;
} else {
endsZero = (e... | Number of Unique Good Subsequences |
Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.
Example 1:
Input: n = 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
Example 2:
Input: n = 1
Output: 9
... | class Solution:
def largestPalindrome(self, n: int) -> int:
return [0, 9, 987, 123, 597, 677, 1218, 877, 475][n]
def isPalindrome(x):
return str(x) == str(x)[::-1]
def solve(n):
best = 0
for i in range(10**n-1, 0, -1):
for j in range(max(i, (best-1)//i+... | class Solution {
public int largestPalindrome(int n) {
if(n == 1 ){
return 9;
}
if(n == 2){
return 987;
}
if(n == 3){
return 123;
}
if(n == 4){
return 597;
}
if(n == 5){
return 677;
... | class Solution {
public:
int largestPalindrome(int n) {
if(n==1)
{
return 9;
}
int hi=pow(10,n)-1;
int lo=pow(10,n-1);
int kk=1337;
for(int i=hi;i>=lo;i--)
{
string s=to_string(i);
string k=s;
reverse(k.b... | /**
* @param {number} n
* @return {number}
*/
var largestPalindrome = function(n) {
if (n === 1) return 9;
let hi = BigInt(Math.pow(10, n) - 1);
let num = hi;
while(num > 0) {
num -= 1n;
const palindrome = BigInt(String(num) + String(num).split('').reverse().join(''));
for (le... | Largest Palindrome Product |
Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand.
Answers within 10-5 of the actual value will be accepted as correct.
Example 1:
Input: hour = 12, minutes = 30
Output: 165
Example 2:
Input: hour = 3, minutes = 30
Output: 75
Example 3:... | class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
x = abs(minutes * 6 -(hour * 30 + minutes/2))
return min(360-x , x) | class Solution {
public double angleClock(int hour, int minutes) {
// Position of hour hand in a circle of 0 - 59
double hrPos = 5 * (hour % 12);
// Adjust hour hand position according to minute hand
hrPos += (5 * minutes/60.0);
double units = Math.abs(minutes - hrPos);
... | class Solution {
public:
double angleClock(int hour, int minutes) {
double hourAngle = 30*(double(hour) + double(minutes/60.0));
double minuteAngle = 6 * (double)minutes;
return 180 - abs(180 - abs(minuteAngle - hourAngle));
}
}; | var angleClock = function(hour, minutes) {
const angle = Math.abs((hour * 30) - 5.5 * minutes)
return angle > 180 ? 360 - angle : angle
}; | Angle Between Hands of a Clock |
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "1... | class Solution:
def numDecodings(self, s: str) -> int:
if s[0] == '0' or '00' in s:
return 0
l = len(s)
if l == 1:
return 1
elif l == 2:
if s[1] == '0':
if s[0] == '1' or s[0] == '2':
return 1
els... | class Solution {
public int numDecodings(String s) {
int[]dp = new int[s.length() + 1];
dp[0] = 1;
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for(int i = 2;i<=s.length();i++) {
int oneDigit = Integer.valueOf(s.substring(i-1,i));
int twoDigit = Integer.valueO... | class Solution {
public:
int numDecodings(string s) {
if(s[0] == 0)
return 0;
int n = s.length();
vector<int> dp(n+1, 0);
//Storing DP[n-1]
if(s[n-1] == '0' )
dp[n-1] = 0;
else
dp[n-1] = 1;
if(n =... | var numDecodings = function(s) {
let dp = Array(s.length).fill(0); // dp[i] means, the total ways of decode for substring up to i
dp[0] = (s[0] !== '0') ? 1 : 0;
for(let i = 1; i < s.length; i++){
//case1
if(s[i] !== '0'){
dp[i] = dp[i - 1];
}
//case2
if(s[i-1] =... | Decode Ways |
Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false.
Example 1:
Input: s = "1001"
Output: false
Explanation: The ones do not form a contiguous segment.
Example 2:
Input: s = "110"
Output: true
Constraints:
... | class Solution:
def checkOnesSegment(self, s: str) -> bool:
return "01" not in s | class Solution {
public boolean checkOnesSegment(String s) {
return !s.contains("01");
}
} | class Solution {
public:
bool checkOnesSegment(string s) {
for(int i = 1; i < s.size(); i++){
if(s[i - 1] == '0' and s[i] == '1'){
return false;
}
}
return true;
}
}; | var checkOnesSegment = function(s) {
return s.indexOf("01") == -1
}; | Check if Binary String Has at Most One Segment of Ones |
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums... | class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
n = len(nums)
stack = []
next_greater = [n] * n
prev_greater = [-1] * n
for i in range(n):
while len(stack) > 0 and nums[i] > nums[stack[-1]]:
curr = st... | class Solution {
public int numSubarrayBoundedMax(int[] nums, int left, int right) {
int res = 0;
int s = -1;
int e = -1;
for(int i=0;i<nums.length;i++){
if(nums[i] >= left && nums[i] <= right){
e = i;
}else if(nums[i] > right){
... | class Solution {
public:
int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {
int ans = 0; // store ans
int j=-1; // starting window
int sub = 0; // if current element is less than left bound then count how may element before current element which is less than left and must be... | var numSubarrayBoundedMax = function(nums, left, right) {
// si is start index
// ei is end index
let si=0, ei=0, finalCount=0, currentCount=0;
while(ei<nums.length){ // moving ei till length of array
if(left<=nums[ei] && nums[ei]<=right) // considering case number falls in the range
... | Number of Subarrays with Bounded Maximum |
Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:
1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)
Updates all values with newValue in the subrectangle whose upper left coordinate i... | class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.rectangle = rectangle
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
for i in range(row1,row2+1):
for j in range(col1,col2+1):
self.rect... | class SubrectangleQueries {
int[][] rectangle;
public SubrectangleQueries(int[][] rectangle) {
this.rectangle = rectangle;
}
public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
for(int i=row1;i<=row2;i++){
for(int j=col1;j<=col2;j++){
... | class SubrectangleQueries {
public:
vector<vector<int>> rect;
SubrectangleQueries(vector<vector<int>>& rectangle) {
rect= rectangle;
}
void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
for(int i=row1; i<=row2; ++i){
for(int j=col1; j<=col2; ... | /**
* @param {number[][]} rectangle
*/
var SubrectangleQueries = function(rectangle) {
this.rectangle = rectangle;
};
/**
* @param {number} row1
* @param {number} col1
* @param {number} row2
* @param {number} col2
* @param {number} newValue
* @return {void}
*/
SubrectangleQueries.prototype.updateSubr... | Subrectangle Queries |
You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.)
Return the minimum number of operations to reduce the sum of nums by at least half.
Example 1:
... | class Solution:
def halveArray(self, nums: List[int]) -> int:
# Creating empty heap
maxHeap = []
heapify(maxHeap) # Creates minHeap
totalSum = 0
for i in nums:
# Adding items to the heap using heappush
# for maxHeap, function by multiplying t... | class Solution {
public int halveArray(int[] nums) {
PriorityQueue<Double> q = new PriorityQueue<>(Collections.reverseOrder());
double sum=0;
for(int i:nums){
sum+=(double)i;
q.add((double)i);
}
int res=0;
double req = sum;
while(sum > ... | class Solution {
public:
int halveArray(vector<int>& nums) {
priority_queue<double> pq;
double totalSum = 0;
double requiredSum = 0;
for(auto x: nums){
totalSum += x;
pq.push(x);
}
requiredSum = totalSum/2;
int minOps = 0;
wh... | var halveArray = function(nums) {
const n = nums.length;
const maxHeap = new MaxPriorityQueue({ priority: x => x });
let startSum = 0;
for (const num of nums) {
maxHeap.enqueue(num);
startSum += num;
}
let currSum = startSum;
let numberOfOperations = 0;
while (currSu... | Minimum Operations to Halve Array Sum |
Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input: root = [5,3,6,2,4,null,7], k = 9
Output: true
Example 2:
Input: root = [5,3,6,2,4,null,7], k = 28
Output: false
Constr... | # 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 findTarget(self, root: Optional[TreeNode], k: int) -> bool:
def inorder(root,l):
if ... | class Solution {
Set<Integer> set = new HashSet<>();
public boolean findTarget(TreeNode root, int k) {
if(root == null){
return false;
}
if(set.contains(k-root.val)){
return true;
}
set.add(root.val);
return findTarget(root.left,k) || findT... | class Solution {
public:
int countNodes(TreeNode *root) {
if (root == NULL) {
return 0;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
bool findTarget(TreeNode* root, int k) {
int totalCount = countNodes(root);
int count = 0;
sta... | var findTarget = function(root, k) {
const set = new Set();
const search = (root, k) => {
if (!root) return false;
if (set.has(k - root.val)) return true;
set.add(root.val);
return search(root.left, k) || search(root.right, k);
}
return search(root,k);
}; | Two Sum IV - Input is a BST |
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnNumber = 1
Output: "A"
Example 2:
Input: columnNumber = 28
Output: "AB"
Example 3:
Input:... | class Solution:
def convertToTitle(self, num: int) -> str:
# We make this lookup list, having A-Z in ascending order
alpha = [chr(x) for x in range(ord("A"), ord("Z")+1)] # range(65, 90+1) -> 91-65 = 26
res = ""
while num > 0:
res += alpha[(num-1)%26] # since 0 indexed... | class Solution {
public String convertToTitle(int columnNumber) {
String ans = "";
while(columnNumber > 0){
columnNumber--;
ans = String.valueOf((char)('A' + (int)((26 + (long)columnNumber) % 26))) + ans;
columnNumber /= 26;
}
return ans;
}
} | class Solution {
public:
string convertToTitle(int columnNumber) {
string s = "";
while(columnNumber){
char c = (columnNumber-1)%26+65;
s = c+s;
columnNumber = (columnNumber-1)/26;
}
return s;
}
}; | /**
* @param {number} columnNumber
* @return {string}
*/
var convertToTitle = function(columnNumber) {
let ans = "";
while(columnNumber >0){
let n = (--columnNumber) % 26;
columnNumber = Math.floor(columnNumber/ 26);
// console.log(String.fromCharCode(65+n),)
ans+=String.from... | Excel Sheet Column Title |
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You... | class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
graph = defaultdict(list)
for i,x in enumerate(isConnected):
for j,n in enumerate(x):
if j!=i and n == 1:
graph[i].append(j)
visit = set()
... | class Solution {
public int findCircleNum(int[][] isConnected) {
int size = isConnected.length;
boolean[] isCheck = new boolean[size+1];
int ans = 0;
for(int i=1; i<=size; i++){
if(!isCheck[i]){ // Doing BFS if it's false in isCheck[]
Queue<Integer> q = ... | class Solution {
private:
void dfs(int node,vector<vector<int>> &graph,int n,vector<bool> &vis){
vis[node] = true;
for(int j = 0; j < graph[node].size(); j++){
if(graph[node][j] == 1 and !vis[j]){
dfs(j,graph,n,vis);
}
}
}
public:
int findCi... | function DisjointSet (size) {
this.root = []
this.rank = []
this.size = size
for (let i = 0; i < size; i++) {
this.root.push(i)
this.rank.push(1)
}
this.find = function(x) {
if (x === this.root[x]) {
return x
}
this.root[x] = this.find(this.roo... | Number of Provinces |
You are given an integer array bloomDay, an integer m and an integer k.
You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum nu... | class Solution:
def minDays(self, listOfFlowerBloomDays: List[int], targetNumberOfBouquets: int, flowersPerBouquet: int) -> int:
def numberOfBouquetsWeCanMakeOnThisDay(dayThatWeAreChecking):
currentListOfAdjacentBloomedFlowers = []
numberOfBouquetsWeCanMake... | class Solution {
public int minDays(int[] bloomDay, int m, int k) {
if(m*k > bloomDay.length) return -1;
int low = Integer.MAX_VALUE, high = 0;
for(int i:bloomDay){
low = Math.min(low,i);
high = Math.max(high,i);
}
while(low<=high){
... | class Solution {
public:
bool check(int mid,vector<int> &v, int m, int k)
{
int n=v.size();
int cnt=0;// taking cnt for the no of k adjacent bouquets possible
for(int i=0;i<v.size();i++)
{
if(v[i]<=mid)
{
int c=0;
... | var minDays = function(bloomDay, m, k) {
if (m * k > bloomDay.length) {
return -1;
}
let left = 0;
let right = 0;
for (const day of bloomDay) {
left = Math.min(day, left);
right = Math.max(day, right);
}
let ans = right;
while (left < right) {
const da... | Minimum Number of Days to Make m Bouquets |
There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.
The rules o... | class Solution:
def findTheWinner(self, n: int, k: int) -> int:
ls=list(range(1,n+1))
while len(ls)>1:
i=(k-1)%len(ls)
ls.pop(i)
ls=ls[i:]+ls[:i]
return ls[0] | class Solution {
public int findTheWinner(int n, int k) {
// Initialisation of the LinkedList
LinkedList<Integer> participants = new LinkedList<>();
for (int i = 1; i <= n; i++) {
participants.add(i);
}
int lastKilled = 0;
// Run the game
for (int i = 0; i < n; i++) {
... | class Solution {
public:
int findTheWinner(int n, int k) {
vector<int>temp;
for(int i=1;i<=n;i++) temp.push_back(i);
int i=0;
while(temp.size()>1){
int t=temp.size();
i=(i+k-1)%t;
temp.erase(temp.begin()+i);
}
return *temp.begin(... | /**
* @param {number} n
* @param {number} k
* @return {number}
*/
var findTheWinner = function(n, k) {
let friends = Array.from({length: n}, (_, index) => index + 1)
let start = 0;
while(friends.length != 1){
start += (k - 1)
start = start % friends.length
friends.splice(start,1)... | Find the Winner of the Circular Game |
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and... | class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
# strategy is greedy solution:
# calculate local maximum for each interval: (b-a)//2
# then take max of local maximums
# the solution is O(n)
# I find this solution clear, but uses 5 passes
... | class Solution {
public int maxDistToClosest(int[] seats) {
int size = seats.length;
int max = 0;
int start = -1;
int end = -1;
for(int i = 0; i<size; i++){
if(seats[i] != 0){
start = end; // update start to end when we have a filled seat.
... | class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
vector<int> d;
int cnt = -1, ans = 0;
for(int i=0; i<seats.size(); i++) {
cnt++;
if(seats[i]) d.push_back(cnt), cnt = 0;
}
d.push_back(cnt);
for(int i=0; i<d.size(); i++) {
... | /**
* @param {number[]} seats
* @return {number}
*/
var maxDistToClosest = function(seats) {
let arr = seats.join('').split('1');
for(let i = 0; i < arr.length;i++){
if(arr[i] == '')
arr[i] = 0;
else{
let middle = true;
if(i == 0 || i == arr.length-1){
... | Maximize Distance to Closest Person |
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "God Ding"
Output: "doG gniD"
Constraints:
1 <=... | class Solution:
def reverseWords(self, s: str) -> str:
s = s + ' '
l = len(s)
t = ''
w = ''
for i in range(l):
if s[i]!=' ':
t = s[i] + t # t stores the word in reverse order
else:
# w stores the reversed word in the same order
... | class Solution {
public String reverseWords(String s) {
if(s == null || s.trim().equals("")){
return null;
}
String [] words = s.split(" ");
StringBuilder resultBuilder = new StringBuilder();
for(String word: words){
for(int i = word.length() - 1; i>=0... | Time: O(n+n) Space: O(1)
class Solution {
public:
string reverseWords(string s) {
int i,j;
for( i=0,j=0;i<size(s);i++){
if(s[i]==' '){
reverse(begin(s)+j,begin(s)+i);
j=i+1;
}
}
reverse(begin(s)+j,end(s));
return s;
... | var reverseWords = function(s) {
// make array of the words from s
let words = s.split(" ");
for (let i in words) {
// replace words[i] with words[i] but reversed
words.splice(i, 1, words[i].split("").reverse().join(""))
} return words.join(" ");
}; | Reverse Words in a String III |
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.
Given the two integers m and n, return the number of possible un... | class Solution:
def uniquePaths(self, m: int, n: int) -> int:
@cache
def dfs(i ,j):
if i == 0 and j == 0: return 1
elif i < 0 or j < 0: return 0
return dfs(i-1, j) + dfs(i, j-1)
return dfs(m-1, n-1) | class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for(int i = 0; i < m; i ++) {
for(int j = 0; j < n; j ++) {
dp[i][j] = -1;
}
}
return helper(m, 0, n, 0, dp);
}
private int helpe... | #define vi vector<int>
#define vvi vector<vi>
class Solution {
public:
int countPath(vvi& dp,int r,int c, int m , int n){
if(m==r-1 || n==c-1)
return 1;
if(dp[m][n]!=-1)
return dp[m][n];
return dp[m][n] = countPath(dp,r,c,m+1,n) + countPat... | var uniquePaths = function(m, n) {
let count = Array(m)
for(let i=0; i<m; i++) count[i] = Array(n)
for(let i=0; i<m; i++){
for(let j=0; j<n; j++){
if(i == 0 || j == 0) count[i][j] = 1
else count[i][j] = count[i][j-1] + count[i-1][j]
}
}
return count[m-1][n-1]
... | Unique Paths |
Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.
The value of |x| is defined as:
x if x >= 0.
-x if x < 0.
Example 1:
Input: nums = [1,2,2,1], k = 1
Output: 4
Explanation: The pairs with an absolute difference of 1 ar... | class Solution:
def countKDifference(self, nums: List[int], k: int) -> int:
seen = defaultdict(int)
counter = 0
for num in nums:
tmp, tmp2 = num - k, num + k
if tmp in seen:
counter += seen[tmp]
if tmp2 in seen:
counter += s... | class Solution {
public int countKDifference(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap<>();
int res = 0;
for(int i = 0;i< nums.length;i++){
if(map.containsKey(nums[i]-k)){
res+= map.get(nums[i]-k);
}
if(map.containsKey(nu... | class Solution {
public:
int countKDifference(vector<int>& nums, int k) {
unordered_map<int, int> freq;
int res = 0;
for (auto num : nums) {
res += freq[num+k] + freq[num-k];
freq[num]++;
}
return res;
}
}; | var countKDifference = function(nums, k) {
nums = nums.sort((b,a) => b- a)
let count = 0;
for(let i = 0; i< nums.length; i++) {
for(let j = i + 1; j< nums.length; j++) {
if(Math.abs(nums[i] - nums[j]) == k) {
count++
}
}
}
return count ;
}; | Count Number of Pairs With Absolute Difference K |
You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.
Return the number of pairs of different nodes that are unreachable from each other.
... | '''
* Make groups of nodes which are connected
eg., edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
0 ---- 2 1 --- 6 3
| |
| |
5 ---- 4
groups will be {0: 4, 1: 2, 3: 1},
i.e 4 nodes are present in group0, 2 nodes are present in group1 and 1 node is present in group3
* Now, we have [4, 2, 1] as n... | class Solution {
public long countPairs(int n, int[][] edges) {
//Building Graph
ArrayList < ArrayList < Integer >> graph = new ArrayList < > ();
for (int i = 0; i < n; i++) graph.add(new ArrayList < Integer > ());
for (int arr[]: edges) {
graph.get(arr[0]).add(arr[1]);
graph.get(arr[1]).a... | class Solution {
public:
typedef long long ll;
void dfs(int node, unordered_map<int,vector<int>>& m, ll& cnt, vector<int>& vis){
vis[node] = 1;
cnt++;
for(auto& i: m[node]){
if(vis[i]==0) dfs(i,m,cnt,vis);
}
}
long long countPairs(int n, vector<vector<int>>... | var countPairs = function(n, edges) {
const adj = [];
for (let i = 0; i < n; i++) {
adj.push([]);
}
for (let [from, to] of edges) {
adj[from].push(to);
adj[to].push(from);
}
const visited = new Set();
function dfs(from) {
visited.add(from);
... | Count Unreachable Pairs of Nodes in an Undirected Graph |
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).
Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
Example 1:
Input: a =... | class Solution:
def minFlips(self, a: int, b: int, c: int) -> int:
res = 0
for i in range(32):
if (a & 1) | (b & 1) != (c & 1):
if (c & 1) == 1: # (a & 1) | (b & 1) should be == 1 ; so changing any of a, b we can get 1
res += 1
else: # ... | class Solution {
public int minFlips(int a, int b, int c) {
int j=-1;
int x=a|b;
int count=0;
while(c!=0 || x!=0){
j++;
int aa=x%2;
int bb=c%2;
if(aa==0 && bb==1)count++;
else if(aa==1 && bb==0) count+=funcount(j,a,b);
... | class Solution {
public:
int minFlips(int a, int b, int c) {
int changeBits = 0;
for(int i=0; i<32; i++){
int lastBitA = 0;
int lastBitB = 0;
int lastBitC = 0;
if(((a >> i) & 1) == 1){
lastBitA = 1;
}
if (((b >>... | var minFlips = function(a, b, c) {
let ans = 0;
for(let bit = 0; bit < 32; bit++) {
let bit_a = (a >> bit)&1, bit_b = (b >> bit)&1, bit_c = (c >> bit)&1;
if(bit_c !== (bit_a | bit_b)) {
if(bit_c === 1) { //a b will be 0 0
ans += 1;
} else { //a b -> 0 1 ->... | Minimum Flips to Make a OR b Equal to c |
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.
A string is called balanced if and only if:
It is the empty string, or
It can be written as AB, where both A and B are balanced strings, or
It can be written as [C], where... | class Solution:
def minSwaps(self, s: str) -> int:
res, bal = 0, 0
for ch in s:
bal += 1 if ch == '[' else -1
if bal == -1:
res += 1
bal = 1
return res | class Solution {
public int minSwaps(String s) {
// remove the balanced part from the given string
Stack<Character> stack = new Stack<>();
for(char ch : s.toCharArray()) {
if(ch == '[')
stack.push(ch);
else {
if(!stack.isEmpty() && stac... | class Solution {
public:
int minSwaps(string s) {
int ans=0;
stack<char> stack;
for(int i=0;i<s.length();i++){
if(s[i]=='['){
stack.push(s[i]);
}
if(s[i]==']' && stack.size()!=0 && stack.top()=='['){
stack.pop();
... | /**
* @param {string} s
* @return {number}
*/
var minSwaps = function(s) {
let stk = []
for(let c of s){
if(stk && c == ']') stk.pop()
else if(c == '[') stk.push(c)
}
return (stk.length) / 2
}; | Minimum Number of Swaps to Make the String Balanced |
Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it... | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
adj = [[] for i in range(n)]
for u,v in edges:
adj[u-1].append(v-1)
adj[v-1].append(u-1)
def f(u,p,tt):
if(u==target-1): return tt==0 or len(adj[u])==(p>=... | class Solution {
public double frogPosition(int n, int[][] edges, int t, int target) {
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++) graph.add(new ArrayList<>());
for(int i=0;i<edges.length;i++) {
graph.get(edges[i][0]).add(edges[i... | class Solution {
public:
double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
unordered_map<int, vector<int>> adjList;
for(const auto& edge : edges) {
adjList[edge[0]].push_back(edge[1]);
adjList[edge[1]].push_back(edge[0]);
}
// BFS wa... | /**
* @param {number} n
* @param {number[][]} edges
* @param {number} t
* @param {number} target
* @return {number}
*/
function dfs(n, map, t, target, visited, prop) {
// edge case1: if run out of steps, cannot find target
if(t === 0 && n !== target) return 0;
// edge case2: if run out of steps, but f... | Frog Position After T Seconds |
There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.
You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an ob... | class Solution:
def minSideJumps(self, obstacles: List[int]) -> int:
"""
# TLE Recursion DP
@cache
def dp(curr_lane = 2, point = 0):
if point == len(obstacles)-1:
return 0
if obstacles[point+1] == curr_lane:
return min(... | class Solution {
public int minSideJumps(int[] obstacles) {
int[] dp = new int[]{1, 0, 1};
for(int i=1; i<obstacles.length; i++){
switch(obstacles[i]){
case 0:
dp[0] = min(dp[0], dp[1]+1, dp[2]+1);
dp[1] = min(dp[0]+1, dp[1], dp[2]+... | class Solution {
public:
int func(int i,int l,vector<int>&obstacles,vector<vector<int>>&dp){
if(i==obstacles.size()-2){
if(obstacles[i+1]==l)return 1;
return 0;
}
if(dp[i][l]!=-1)return dp[i][l];
if(obstacles[i+1]!=l){
return dp[i][l] = func(i+1,... | var minSideJumps = function(obstacles) {
// create a dp cache for tabulation
const dp = [...obstacles].map(() => new Array(4).fill(Infinity));
// initialize the first positions
dp[0][2] = 0;
for (const lane of [1,3]) {
if (obstacles[0] === lane) continue;
dp[0][lane] = 1;
}
... | Minimum Sideway Jumps |
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.
In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one b... | class Solution:
def minOperations(self, boxes: str) -> List[int]:
ans = [0]*len(boxes)
leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)
for i in range(1, n):
if boxes[i-1] == '1': leftCount += 1
leftCost += leftCount # each step move to right, th... | class Solution{
public int[] minOperations(String boxes){
int n = boxes.length();
int[] ans = new int[n];
for(int i=0; i<n; i++){
int t = 0;
for(int j=0; j<n; j++){
char c = boxes.charAt(j);
if(c=='1') t += Math.abs(i-j);
}
... | class Solution {
public:
vector<int> minOperations(string boxes) {
int n = boxes.size();
vector<int> ans;
for(int i = 0; i < n; i++)
{
int res = 0;
for(int j = 0; j < n; j++)
{
if(boxes[j] == '1')
{
... | var minOperations = function(boxes) {
const ans = new Array(boxes.length).fill(0);
let ballsLeft = 0, ballsRight = 0;
let movesLeft = 0, movesRight = 0;
const len = boxes.length - 1;
for(let i = 0; i <= len; i++) {
movesLeft += ballsLeft;
movesRight += ballsRight;
... | Minimum Number of Operations to Move All Balls to Each Box |
The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.
The knight has an initial health po... | class Solution:
def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
dp = defaultdict(lambda: inf)
dp[(len(dungeon), len(dungeon[0]) - 1)] = 1
for i in range(len(dungeon) - 1, -1, -1):
for j in range(len(dungeon[0]) - 1, -1, -1):
dp[(i, j)] = min(dp[(i + 1, j)], dp[(i, j + 1)]) - dungeon[i... | class Solution {
Integer[][] min;
public int calculateMinimumHP(int[][] dungeon) {
min = new Integer[dungeon.length][dungeon[0].length];
int answer = min(0, 0, dungeon);
return Math.max(answer, 1);
}
public int min(int i, int j, int[][] dungeon){
if(i > dungeon.length - 1... | class Solution {
public:
int solve(int i, int j, int m , int n, vector<vector<int>> &grid)
{
// if we come out of the grid simply return a large value
if(i >= m || j >= n)
return INT_MAX;
// calucate health by the 2 possible ways
int down = solve(i + 1, j, m,... | /**
* The dynamic programming solution.
*
* Time Complexity: O(m*n)
* Space Complexity: O(1)
*
* @param {number[][]} dungeon
* @return {number}
*/
var calculateMinimumHP = function(dungeon) {
const m = dungeon.length
const n = dungeon[0].length
const ii = m - 1
const jj = n - 1
for (let i = ii; i >= 0... | Dungeon Game |
You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.
A row i is weaker than a row j if one of the following is true:
The number of sold... | class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
row = []
for i in range(len(mat)):
row.append((sum(mat[i]), i))
row.sort()
ans = [idx for (val, idx) in row[:k]]
return ans | class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
Map<Integer, Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
int[] arr = new int[k];
for (int i = 0; i < mat.length; i++){
int n = getBits(mat[i]);
map.put(i, n);
... | class Solution {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
// <idx, count>
vector<pair<int,int>> freqMapper;
int civilian = 0;
for(int i=0; i<mat.size(); ++i) {
int degree = count(mat[i].begin(), mat[i].end(), civilian);
freqMapper.pu... | /**
* @param {number[][]} mat
* @param {number} k
* @return {number[]}
* S: O(N)
* T: O(N*logN)
*/
var kWeakestRows = function(mat, k) {
return mat.reduce((acc, row, index) => {
let left = 0;
let right = row.length - 1;
while(left <= right) {
let mid = Math.floor( (left +... | The K Weakest Rows in a Matrix |
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
m == matrix.length
n == matr... | class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
col, row = len(matrix[0]), len(matrix)
l, t, r, b = 0, 0, col - 1, row - 1
res = []
while l <= r and t <= b:
for i in range(l, r):
res.append(matrix[t][i])
for i in ra... | class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
int top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1;
while (top <= bottom && left <= right)
{
for (int i = left; i <= right; i++)
... | class Solution {
public:
vector<int> _res;
vector<vector<bool>> _visited;
void spin(vector<vector<int>>& matrix, int direction, int i, int j) {
_visited[i][j] = true;
_res.push_back(matrix[i][j]);
switch (direction){
// left to right
case 0:
... | /**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
let [top, bot, left, right, ans] = [0, matrix.length - 1, 0, matrix[0].length - 1,[]]
while ((top <= bot) && (left <= right)) {
for (let j = left; j <= right; j++) {
ans.push(matrix[top][j])
... | Spiral Matrix |
Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Implement the Solution class:
Solution(int[] nums) Initializes the object with the array nums.
int pick(int target) Picks a random index i f... | class Solution:
def __init__(self, nums: List[int]):
#self.nums = nums
#create a hash of values with their list of indices
self.map = defaultdict(list)
for i,v in enumerate(nums):
self.map[v].append(i)
def pick(self, target: int) -> int:
return rand... | class Solution {
ArrayList<Integer> ll=new ArrayList<>();
public Solution(int[] nums) {
for(int i=0;i<nums.length;i++){
ll.add(nums[i]);
}
}
public int pick(int target) {
double a=Math.random();
int n=(int)(a*this.ll.size());
while(this.ll.get... | class Solution {
unordered_map<int,vector<int>> itemIndicies;
public:
Solution(vector<int>& nums)
{
srand(time(NULL));
for (int i = 0; i < nums.size(); i++)
{
if (itemIndicies.find(nums[i]) == itemIndicies.end())
itemIndicies[nums[i]] = {i};
... | var Solution = function(nums) {
this.map = nums.reduce((result, num, index) => {
const value = result.get(num) ?? [];
value.push(index);
result.set(num, value);
return result;
}, new Map());
};
Solution.prototype.pick = function(target) {
const pick = this.map.get(target);
... | Random Pick Index |
Given a string s, return true if s is a good string, or false otherwise.
A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).
Example 1:
Input: s = "abacbc"
Output: true
Explanation: The characters that appear in s are 'a', 'b', and 'c'. All... | class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
return len(set(Counter(s).values())) == 1 | class Solution {
public boolean areOccurrencesEqual(String s) {
int[] freq = new int[26];
for (int i = 0; i < s.length(); i++) freq[s.charAt(i)-'a']++;
int val = freq[s.charAt(0) - 'a'];
for (int i = 0; i < 26; i++)
if (freq[i] != 0 && freq[i] != val) return fal... | class Solution {
public:
bool areOccurrencesEqual(string s) {
unordered_map<char, int> freq;
for (auto c : s) freq[c]++;
int val = freq[s[0]];
for (auto [a, b] : freq) if (b != val) return false;
return true;
}
}; | var areOccurrencesEqual = function(s) {
var freq = {}
for (let c of s) freq[c] = (freq[c] || 0) + 1
var val = freq[s[0]]
for (let c in freq) if (freq[c] && freq[c] != val) return false;
return true;
}; | Check if All Characters Have Equal Number of Occurrences |
Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.
A string is said to be palindrome if it the same string when reversed.
Example 1:
Input: s = "abcbdd"
Output: true
Explanation: "abcbdd" = "a" + "bcb" + "dd", and al... | class Solution:
def checkPartitioning(self, s: str) -> bool:
n = len(s)
@lru_cache(None)
def pal(i,j):
if i == j:
return True
if s[i] != s[j]:
return False
if i+1 == j:
return True
else:
... | class Solution {
public boolean checkPartitioning(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
for(int g=0 ; g<n ; g++){
for(int i=0, j=g ; j<n ; j++, i++){
if(g == 0)
dp[i][j] = true;
else if(g == 1)
... | class Solution {
public:
vector<vector<int>> dp1;
bool isPalindrome(string& s, int i, int j) {
if (i >= j) return true;
if (dp1[i][j] != -1) return dp1[i][j];
if (s[i] == s[j]) return dp1[i][j] = isPalindrome(s, i + 1, j - 1);
return dp1[i][j] = false;
}
bool checkPartitioning(string s) {
int n = s.size()... | /**
* @param {string} s
* @return {boolean}
*/
var checkPartitioning = function(s) {
// create a dp that will represent the starting and ending index of a substring
// if dp[i][j] is true that means that the string starting from i and ending at j is a palindrome
const dp = new Array(s.length).fill(null).... | Palindrome Partitioning IV |
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
| class Solution:
def generateParenthesis(self, n: int) -> list[str]:
# Initialize the result
res = []
# Recursively go through all possible combinations
def add(open, close, partialRes):
nonlocal res
# If we have added opening and closing parentheses n time... | class Solution {
List<String> s = new ArrayList<>();
public void get(int n, int x, String p)
{
if(n==0 && x==0)
{
s.add(p);
return;
}
if(n==0)
{
get(n,x-1,p+")");
}
else if(x==0)
{
get(n-1,x+1,p+"... | class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
generate(ans,"",n,n);
return ans;
}
void generate(vector<string> &ans,string s,int open,int close)
{
if(open == 0 && close == 0)
{
ans.push_... | var generateParenthesis = function(n) {
let ans = []
generate_parenthisis(n, 0, 0, "")
return ans
function generate_parenthisis(n, open, close, res){
if(open==n && close == n){
ans.push(res)
return
}
if(open<n){
generate_parenthisis(n, open+... | Generate Parentheses |
The bitwise AND of an array nums is the bitwise AND of all integers in nums.
For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.
Also, for nums = [7], the bitwise AND is 7.
You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of nu... | class Solution:
def largestCombination(self, candidates: List[int]) -> int:
return max(sum(n & (1 << i) > 0 for n in candidates) for i in range(0, 24)) | class Solution {
public static int largestCombination(int[] candidates) {
int arr[] = new int[32];
for (int i = 0; i < candidates.length; i++) {
String temp = Integer.toBinaryString(candidates[i]);
int n = temp.length();
int index = 0;
while (n-- > 0) {
arr[index++] += temp.charAt(n) - '0';
}
... | class Solution {
public:
int largestCombination(vector<int>& candidates) {
vector<int> bits(32);
for(int i = 0; i < candidates.size(); i++){
int temp = 31;
while(candidates[i] > 0){
bits[temp] += candidates[i] % 2;
candidates[i] = candidates[i]... | var largestCombination = function(candidates) {
const indexArr=Array(24).fill(0)
for(let candidate of candidates){
let index =0
while(candidate>0){
if((candidate&1)===1)indexArr[index]+=1
candidate>>>=1
index++
}
}
return Math.max(...indexArr)
}; | Largest Combination With Bitwise AND Greater Than Zero |
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is... | def cal(ele):
return ele[0]**2 +ele[1]**2
def partition(arr,start,end):
# We must take a pivot element randomly to make Quick select work faster
rdIdx = randint(start,end)
arr[rdIdx],arr[end] = arr[end],arr[rdIdx]
pivot = arr[end]
i = start-1
pivot_dis = cal(pivot)
for j in range(start,... | class Solution {
static class Distance {
int i;
int j;
double dist;
public Distance(int i, int j, double dist) {
this.i = i;
this.j = j;
this.dist = dist;
}
}
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<... | class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k)
{
//max heap
priority_queue<pair<int,pair<int,int>>> pq;//first integer is distance(no need for sq root as comparison is same and next part of pair is coordinate
int n= points.size();
for(in... | /**
* @param {number[][]} points
* @param {number} k
* @return {number[][]}
*/
var kClosest = function(points, k) {
let res = [];
let hashMap = new Map();
for(let i = 0; i < points.length; i++) {
//store the distance and the index of the points in a map
const dis = calcDis(points[i]);
... | K Closest Points to Origin |
Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.
You can return the answer in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explan... | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
# DFS to make the adj List
adjList = defaultdict(list)
def dfs(node):
if not node:
return
if node.left:
adjList[node].append(node.left)
... | class Solution {
public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
HashMap<TreeNode,TreeNode> map=new HashMap<>();
get_parent(root,map);
Queue<TreeNode> q=new LinkedList<>();
q.add(target);
int distance=0;
HashSet<TreeNode> visited=new HashSet<>(... | void makeParent(TreeNode *root, unordered_map<TreeNode*, TreeNode*> &parent)
{
queue<TreeNode*> q;
q.push(root);
while(q.empty()==false)
{
TreeNode *curr = q.front();
q.pop();
if(curr->left!=NULL)
{
parent[curr->left] = curr;
q.push(curr->left);
}
if(curr->right!=NULL)
{
parent[curr->right... | /**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} target
* @param {number} k
* @return {number[]}
*/
var distanceK = function(root, target, k) {
if(k === 0)
return [target.... | All Nodes Distance K in Binary Tree |
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Ex... | class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
cur = dummy = ListNode()
while list1 and list2:
if list1.val < list2.val:
cur.next = list1
list1, cur = list1.next, list1
... | class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2)
{
if(list1==null && list2==null)
return null;
if(list1 == null)
return list2;
if(list2 == null)
return list1;
ListNode newHead = new ListNode();
ListNode ne... | class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode dummy(INT_MIN);
ListNode *tail = &dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
... | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function(list1, list2) {
if(!list1) ... | Merge Two Sorted Lists |
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
A node is a terminal node if there are no outgoing e... | import collections
class Solution:
def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:
n = len(graph)
ans = []
for i in range(n):
if not graph[i]:
ans.append(i)
def loop(key, loops):
loops.append(key)
... | class Solution {
public List<Integer> eventualSafeNodes(int[][] graph) {
int n=graph.length;
List<Integer> ans=new ArrayList<>();
boolean visited[]=new boolean[n];
boolean dfsVisited[]=new boolean[n];
boolean nodeCycles[]=new boolean[n];
for(int i=0;i<n;i++){
if(visited[i]==false){... | class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
int n=graph.size();
vector<bool> vis(n, false), curr_vis(n, false), safe(n, true);
for(int i=0; i<n; i++)
if(!vis[i])
dfs(i, vis, curr_vis, safe, graph);
vector<int> ans... | /**
* @param {number[][]} graph
* @return {number[]}
*/
var eventualSafeNodes = function(graph) {
const ans = [];
const map = new Map();
for(let i=0; i<graph.length; i++) {
if(dfs(graph, i, map)) {
ans.push(i);
}
}
return ans;
};
var dfs = function(graph, node, map) {... | Find Eventual Safe States |
Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.
The edges... | class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
graph_map = {i: set() for i in range(n)}
for edge in edges:
graph_map[edge[0]].add(edge[1])
graph_map[edge[1]].add(edge[0])
self.result = set()
visited = set()
... | class Solution {
public int minTime(int n, int[][] edges, List<Boolean> hasApple) {
HashMap<Integer,List<Integer>> graph = new HashMap<>(n);
for(int edge[] : edges){
int a = edge[0], b = edge[1];
graph.putIfAbsent(a, new LinkedList<>());
graph.putIfAbsent(b, new L... | class DSU{
private:
vector<int> parent,rank ;
public:
DSU(int n){
rank.resize(n,1) ;
parent.resize(n) ;
iota(begin(parent),end(parent),0) ;
}
int find_parent(int node){
if(node == parent[node]) return node ;
return parent[node] = find_parent(parent[node]) ;
}... | var cnvrtAdjLst = (mat) => {//converts the list of edges to adjacency list
let map = new Map();
for(let i=0; i<mat.length; i++){
let [p,c] = mat[i];
if(map[p]===undefined) map[p] = [c];
else map[p].push(c);
if(map[c]===undefined) map[c] = [p];
else map[c].push(p);
... | Minimum Time to Collect All Apples in a Tree |
There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
A team is valid if: (rating[i] < rating[j] < rating[k]) ... | class Solution:
def numTeams(self, ratings: List[int]) -> int:
upper_dps = [0 for _ in range(len(ratings))]
lower_dps = [0 for _ in range(len(ratings))]
count = 0
for i in range(len(ratings)):
for j in range(i):
if ratings[j] < ratings[i]:
... | // Smaller * Larger Solution
// sum of #smaller * #larger
// Time complexity: O(N^2)
// Space complexity: O(1)
class Solution {
public int numTeams(int[] rating) {
final int N = rating.length;
int res = 0;
for (int i = 1; i < N; i++) {
res += smaller(rating, i, -1) * larger(ratin... | class Solution {
public:
int numTeams(vector<int>& rating) {
int i, j, n = rating.size(), ans = 0;
vector<int> grt(n, 0), les(n, 0);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(rating[j] > rating[i])
grt[i] += 1;
... | // counting bigger / smaller elements
// if after rating[i] has X bigger elements,
// and each element has Y bigger elements after them
// hence total elements that has i < j < k and rating[i] < rating[j] < rating[k]
// same for the number of smaller elements
// so the key point here is to know how many elements
// tha... | Count Number of Teams |
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.
The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
 ... | class Solution:
def canBeIncreasing(self, nums: List[int]) -> bool:
indx = -1
count = 0
n = len(nums)
# count the number of non-increasing elements
for i in range(n-1):
if nums[i] >= nums[i+1]:
indx = i
count += 1
... | class Solution {
public boolean canBeIncreasing(int[] nums) {
int count=0;
int p=0;
for(int i=0;i<nums.length-1;i++){
if(nums[i]>nums[i+1] || nums[i]==nums[i+1]) {
count++;
p=i;
}
}
if(count>1) return false;
else... | class Solution {
public:
bool canBeIncreasing(vector<int>& nums) {
int count = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] <= nums[i - 1]) {
if (count == 1)
return false;
count++;
if (i > 1 && nums[i] <= nums[i - 2] )... | var canBeIncreasing = function(nums) {
for (let i = 1, used = false, prev = nums[0]; i < nums.length; i++) {
if (nums[i] > prev) { prev = nums[i]; continue }
if (used) return false;
used = true;
(i === 1 || nums[i] > nums[i - 2]) && (prev = nums[i]);
}
return true;
}; | Remove One Element to Make the Array Strictly Increasing |
Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.
In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key.
For example, to add the letter 's', Alice has to press '7' four times. Simil... | class Solution(object):
def countTexts(self, pressedKeys):
"""
:type pressedKeys: str
:rtype: int
"""
dp = [1] + [0]*len(pressedKeys)
mod = 10**9 + 7
for i, n in enumerate(pressedKeys):
dp[i+1] = dp[i]
# check if is continous
... | class Solution {
int mod = (1000000007);
public int countTexts(String pressedKeys) {
int[] key = new int[] { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4 };
int n = pressedKeys.length();
return solve(0,pressedKeys,key);
}
public int solve(int ind, String s, int[] key) {
if (ind == s.le... | class Solution {
public:
int mod = 1e9+7;
int solve(string &str, int idx) {
if(idx == str.length()) return 1;
int maxKeyPress = (str[idx] == '7' || str[idx] == '9') ? 4 : 3;
long long currIndex = idx, pressFrequency = 1, ans = 0;
while(pressFrequency <= maxKeyPress && str[currInd... | var countTexts = function(pressedKeys) {
const MOD = 1e9 + 7;
const n = pressedKeys.length;
const dp = new Array(n + 1).fill(0);
dp[0] = 1;
let lastChar = "";
let repeatCount = 0;
for (let i = 1; i <= n; ++i) {
const currChar = pressedKeys[i - 1];
if (currChar != lastChar... | Count Number of Texts |
You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.
Return the minimum number of steps to make t an anagram of s.
An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.
... | class Solution:
def minSteps(self, s: str, t: str) -> int:
for ch in s:
# Find and replace only one occurence of this character in t
t = t.replace(ch, '', 1)
return len(t) | //find the frequency of every letter and check diffrence between the frequency of each letter then divide it by 2 to calculate the minimum number of letter to be changed.
class Solution {
public int minSteps(String s, String t) {
int sf[]=new int[26];
int tf[]=new int[26];
int diff=0;
... | class Solution {
public:
int minSteps(string s, string t) {
int count = 0, length = s.length();
vector<int> vec1(26, 0), vec2(26, 0);
for(int i = 0; i < length; ++i){
vec1[s[i] - 'a']++;
vec2[t[i] - 'a']++;
}
for(int i = 0; i < 26; ++i){
if... | var minSteps = function(s, t) {
let hash1 = hash(s);
let hash2 = hash(t);
let steps = 0;
for(let key of Object.keys(hash1)) {
if( hash2[key]) {
hash1[key] = hash1[key] - hash2[key];
}
if( hash1[key] > 0 ) {
steps += hash1[key];
}
}
retur... | Minimum Number of Steps to Make Two Strings Anagram |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.