refactor(work): restructure solution directories with bucket level and add .gitkeep placeholders

This commit is contained in:
Prad Nukala
2026-08-31 10:41:40 -04:00
parent b21ab75e0e
commit 7e46fceb1c
41 changed files with 0 additions and 0 deletions
@@ -0,0 +1,60 @@
"""
11. Container With Most Water
Difficulty: Medium
https://leetcode.com/problems/container-with-most-water/
──────────────────────────────────────────────────
You are given an integer array height of length n. There are n
vertical lines drawn such that the two endpoints of the i^th line are
(i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such
that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array
[1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue
section) the container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
Constraints:
• n == height.length
• 2 <= n <= 10^5
• 0 <= height[i] <= 10^4
"""
class Solution:
def maxArea(self, height: List[int]) -> int: # noqa: F821
res = 0
left = 0
right = len(height) - 1
while left < right:
area = (right - left) * min(height[left], height[right])
res = max(res, area)
if height[left] < height[right]:
left += 1
else:
right -= 1
return res
+89
View File
@@ -0,0 +1,89 @@
"""
15. 3Sum
Difficulty: Medium
https://leetcode.com/problems/3sum/
──────────────────────────────────────────────────
Given an integer array nums, return all the triplets [nums[i],
nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] +
nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets
does not matter.
Example 2:
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
Constraints:
• 3 <= nums.length <= 3000
• -10^5 <= nums[i] <= 10^5
"""
class Solution:
def threeSum(self, nums: list[int]) -> list[list[int]]:
nums.sort()
result = []
n = len(nums)
for i in range(n):
# skip all zero
if i > 0 and nums[i] == nums[i - 1]:
continue
# two pointers
left = i + 1
right = n - 1
target = -nums[i]
while left < right:
current = nums[left] + nums[right]
if current == target:
result.append([nums[i], nums[left], nums[right]])
# skip duplicates
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
# shift pointers
left += 1
right -= 1
# since sorted, if current < target, then move left
elif current < target:
left += 1
# since sorted, if current > target, then move right
else:
right -= 1
return result
@@ -0,0 +1,88 @@
"""
150. Evaluate Reverse Polish Notation
Difficulty: Medium
https://leetcode.com/problems/evaluate-reverse-polish-notation/
──────────────────────────────────────────────────
You are given an array of strings tokens that represents an
arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value
of the expression.
Note that:
• The valid operators are '+', '-', '*', and '/'.
• Each operand may be an integer or another expression.
• The division between two integers always truncates toward zero.
• There will not be any division by zero.
• The input represents a valid arithmetic expression in a reverse
polish notation.
• The answer and all the intermediate calculations can be
represented in a 32-bit integer.
Example 1:
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: tokens =
["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
Constraints:
• 1 <= tokens.length <= 10^4
• tokens[i] is either an operator: "+", "-", "*", or "/", or an
integer in the range [-200, 200].
"""
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
operations = {
"+": lambda x, y: int(x + y),
"-": lambda x, y: int(x - y),
"*": lambda x, y: int(x * y),
"/": lambda x, y: int(x / y),
}
for c in tokens:
if c in operations:
y = stack.pop()
x = stack.pop()
calc_func = operations[c]
result = calc_func(x, y)
stack.append(result)
else:
stack.append(int(c))
return stack[0]
@@ -0,0 +1,75 @@
"""
153. Find Minimum in Rotated Sorted Array
Difficulty: Medium
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
──────────────────────────────────────────────────
Suppose an array of length n sorted in ascending order is rotated
between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7]
might become:
• [4,5,6,7,0,1,2] if it was rotated 4 times.
• [0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time
results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the
minimum element of this array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
Example 2:
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was
rotated 4 times.
Example 3:
Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated
4 times.
Constraints:
• n == nums.length
• 1 <= n <= 5000
• -5000 <= nums[i] <= 5000
• All the integers of nums are unique.
• nums is sorted and rotated between 1 and n times.
"""
class Solution:
def findMin(self, nums: List[int]) -> int:
l, r = 0, len(nums) - 1
lowest_index = -1
while l <= r:
m = (l + r) // 2
if nums[m] <= nums[-1]:
lowest_index = m
r = m - 1
else:
l = m + 1
return nums[lowest_index]
@@ -0,0 +1,73 @@
"""
167. Two Sum II - Input Array Is Sorted
Difficulty: Medium
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
──────────────────────────────────────────────────
Given a 1-indexed array of integers numbers that is already sorted in
non-decreasing order, find two numbers such that they add up to a
specific target number. Let these two numbers be numbers[index1] and
numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers index1 and index2, each
incremented by one, as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You
may not use the same element twice.
Your solution must use only constant extra space.
Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 =
2. We return [1, 2].
Example 2:
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 =
3. We return [1, 3].
Example 3:
Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2
= 2. We return [1, 2].
Constraints:
• 2 <= numbers.length <= 3 * 10^4
• -1000 <= numbers[i] <= 1000
• numbers is sorted in non-decreasing order.
• -1000 <= target <= 1000
• The tests are generated such that there is exactly one solution.
"""
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
i = 0
j = len(numbers) - 1
while i < j:
c = numbers[i] + numbers[j]
if c == target:
return [i + 1, j + 1]
elif c < target:
i+=1
else:
j-=1
return []
@@ -0,0 +1,67 @@
/*
* 238. Product of Array Except Self
* Difficulty: Medium
* https://leetcode.com/problems/product-of-array-except-self/
*
* ──────────────────────────────────────────────────
*
* Given an integer array nums, return an array answer such that
* answer[i] is equal to the product of all the elements of nums except
* nums[i].
*
* The product of any prefix or suffix of nums is guaranteed to fit in a
* 32-bit integer.
*
* You must write an algorithm that runs in O(n) time and without using
* the division operation.
*
*
*
* Example 1:
*
* Input: nums = [1,2,3,4]
* Output: [24,12,8,6]
*
* Example 2:
*
* Input: nums = [-1,1,0,-3,3]
* Output: [0,0,9,0,0]
*
*
*
* Constraints:
*
* • 2 <= nums.length <= 10^5
*
* • -30 <= nums[i] <= 30
*
* • The input is generated such that answer[i] is guaranteed to fit in
* a 32-bit integer.
*
*
*
* Follow up: Can you solve the problem in O(1) extra space complexity?
* (The output array does not count as extra space for space complexity
* analysis.)
*/
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
const n = nums.length;
const answer = new Array(n).fill(1);
const rightArr = new Array(n).fill(1);
for (let i = 1; i < n; i++) {
answer[i] = nums[i - 1] * answer[i - 1];
}
for (let i = n - 2; i >= 0; i--) {
rightArr[i] = nums[i + 1] * rightArr[i + 1];
}
for (let i = 0; i < n; i++) {
answer[i] *= rightArr[i];
}
return answer;
};
@@ -0,0 +1,87 @@
/*
* 33. Search in Rotated Sorted Array
* Difficulty: Medium
* https://leetcode.com/problems/search-in-rotated-sorted-array/
*
* ──────────────────────────────────────────────────
*
* There is an integer array nums sorted in ascending order (with
* distinct values).
*
* Prior to being passed to your function, nums is possibly left rotated
* at an unknown index k (1 <= k < nums.length) such that the resulting
* array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ...,
* nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be left
* rotated by 3 indices and become [4,5,6,7,0,1,2].
*
* Given the array nums after the possible rotation and an integer
* target, return the index of target if it is in nums, or -1 if it is
* not in nums.
*
* You must write an algorithm with O(log n) runtime complexity.
*
*
*
* Example 1:
*
* Input: nums = [4,5,6,7,0,1,2], target = 0
* Output: 4
*
* Example 2:
*
* Input: nums = [4,5,6,7,0,1,2], target = 3
* Output: -1
*
* Example 3:
*
* Input: nums = [1], target = 0
* Output: -1
*
*
*
* Constraints:
*
* • 1 <= nums.length <= 5000
*
* • -10^4 <= nums[i] <= 10^4
*
* • All values of nums are unique.
*
* • nums is an ascending array that is possibly rotated.
*
* • -10^4 <= target <= 10^4
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let l = 0, r = nums.length - 1;
while (l <= r){
let mid = Math.floor((l + r)/2);
if (target === nums[mid]) {
return mid
}
// Left sorted portion
if (nums[l] <= nums[mid]){
if (target > nums[mid] || target < nums[l]){
l = mid + 1;
}else{
r = mid - 1;
}
}
// Right sorted portion
else{
if(target < nums[mid] || target > nums[r]){
r = mid - 1;
}else{
l = mid + 1;
}
}
}
return -1;
};
@@ -0,0 +1,62 @@
/*
* 347. Top K Frequent Elements
* Difficulty: Medium
* https://leetcode.com/problems/top-k-frequent-elements/
*
* ──────────────────────────────────────────────────
*
* Given an integer array nums and an integer k, return the k most
* frequent elements. You may return the answer in any order.
*
*
*
* Example 1:
*
* Input: nums = [1,1,1,2,2,3], k = 2
*
* Output: [1,2]
*
* Example 2:
*
* Input: nums = [1], k = 1
*
* Output: [1]
*
* Example 3:
*
* Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2
*
* Output: [1,2]
*
*
*
* Constraints:
*
* • 1 <= nums.length <= 10^5
*
* • -10^4 <= nums[i] <= 10^4
*
* • k is in the range [1, the number of unique elements in the array].
*
* • It is guaranteed that the answer is unique.
*
*
*
* Follow up: Your algorithm's time complexity must be better than O(n
* log n), where n is the array's size.
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var topKFrequent = function (nums, k) {
const freq = {};
for (let n of nums) freq[n] = (freq[n] || 0) + 1;
return Object.keys(freq)
.map(Number)
.sort((a, b) => freq[b] - freq[a])
.slice(0, k);
};
+69
View File
@@ -0,0 +1,69 @@
/*
* 49. Group Anagrams
* Difficulty: Medium
* https://leetcode.com/problems/group-anagrams/
*
* ──────────────────────────────────────────────────
*
* Given an array of strings strs, group the anagrams together. You can
* return the answer in any order.
*
*
*
* Example 1:
*
* Input: strs = ["eat","tea","tan","ate","nat","bat"]
*
* Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
*
* Explanation:
*
* • There is no string in strs that can be rearranged to form "bat".
*
* • The strings "nat" and "tan" are anagrams as they can be rearranged
* to form each other.
*
* • The strings "ate", "eat", and "tea" are anagrams as they can be
* rearranged to form each other.
*
* Example 2:
*
* Input: strs = [""]
*
* Output: [[""]]
*
* Example 3:
*
* Input: strs = ["a"]
*
* Output: [["a"]]
*
*
*
* Constraints:
*
* • 1 <= strs.length <= 10^4
*
* • 0 <= strs[i].length <= 100
*
* • strs[i] consists of lowercase English letters.
*/
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
let sorted = strs.map(str => str.split("").sort().join(""));
let anagrams = {};
for (let i = 0; i < strs.length; i++){
if(!anagrams[sorted[i]]){
anagrams[sorted[i]] = [strs[i]]
}else{
anagrams[sorted[i]].push(strs[i])
}
}
return Object.values(anagrams);
};
@@ -0,0 +1,59 @@
/*
* 560. Subarray Sum Equals K
* Difficulty: Medium
* https://leetcode.com/problems/subarray-sum-equals-k/
*
* ──────────────────────────────────────────────────
*
* Given an array of integers nums and an integer k, return the total
* number of subarrays whose sum equals to k.
*
* A subarray is a contiguous non-empty sequence of elements within an
* array.
*
*
*
* Example 1:
*
* Input: nums = [1,1,1], k = 2
* Output: 2
*
* Example 2:
*
* Input: nums = [1,2,3], k = 3
* Output: 2
*
*
*
* Constraints:
*
* • 1 <= nums.length <= 2 * 10^4
*
* • -1000 <= nums[i] <= 1000
*
* • -10^7 <= k <= 10^7
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var subarraySum = function(nums, k) {
const map = new Map();
map.set(0, 1);
let sum = 0;
let count = 0;
for (let n of nums){
sum += n;
if(map.has(sum - k)){
count += map.get(sum - k);
}
map.set(sum, (map.get(sum) || 0) + 1);
}
return count
};
@@ -0,0 +1,50 @@
"""
739. Daily Temperatures
Difficulty: Medium
https://leetcode.com/problems/daily-temperatures/
──────────────────────────────────────────────────
Given an array of integers temperatures represents the daily
temperatures, return an array answer such that answer[i] is the number
of days you have to wait after the i^th day to get a warmer
temperature. If there is no future day for which this is possible,
keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]
Constraints:
• 1 <= temperatures.length <= 10^5
• 30 <= temperatures[i] <= 100
"""
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
ans = [0] * len(temperatures)
stack = []
for i, temp in enumerate(temperatures):
while stack and temperatures[stack[-1]] < temp:
prev = stack.pop()
ans[prev] = i - prev
stack.append(i)
return ans
@@ -0,0 +1,74 @@
"""
74. Search a 2D Matrix
Difficulty: Medium
https://leetcode.com/problems/search-a-2d-matrix/
──────────────────────────────────────────────────
You are given an m x n integer matrix matrix with the following two
properties:
• Each row is sorted in non-decreasing order.
• The first integer of each row is greater than the last integer of
the previous row.
Given an integer target, return true if target is in matrix or false
otherwise.
You must write a solution in O(log(m * n)) time complexity.
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
Constraints:
• m == matrix.length
• n == matrix[i].length
• 1 <= m, n <= 100
• -10^4 <= matrix[i][j], target <= 10^4
"""
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
ROWS, COLS = len(matrix), len(matrix[0])
top, bot = 0, ROWS - 1
while top <= bot:
row = (top + bot) // 2
if target > matrix[row][-1]:
top = row + 1
elif target < matrix[row][0]:
bot = row - 1
else:
break
if not (top <= bot):
return False
row = (top + bot) // 2
l, r = 0, COLS - 1
while l <= r:
m = (l + r) // 2
if target > matrix[row][m]:
l = m + 1
elif target < matrix[row][m]:
r = m - 1
else:
return True
return False
+98
View File
@@ -0,0 +1,98 @@
"""
853. Car Fleet
Difficulty: Medium
https://leetcode.com/problems/car-fleet/
──────────────────────────────────────────────────
There are n cars at given miles away from the starting mile 0,
traveling to reach the mile target.
You are given two integer arrays position and speed, both of length
n, where position[i] is the starting mile of the i^th car and speed[i]
is the speed of the i^th car in miles per hour.
A car cannot pass another car, but it can catch up and then travel
next to it at the speed of the slower car.
A car fleet is a single car or a group of cars driving next to each
other. The speed of the car fleet is the minimum speed of any car in
the fleet.
If a car catches up to a car fleet at the mile target, it will still
be considered as part of the car fleet.
Return the number of car fleets that will arrive at the destination.
Example 1:
Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3
Explanation:
• The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet,
meeting each other at 12. The fleet forms at target.
• The car starting at 0 (speed 1) does not catch up to any other
car, so it is a fleet by itself.
• The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet,
meeting each other at 6. The fleet moves at speed 1 until it reaches
target.
Example 2:
Input: target = 10, position = [3], speed = [3]
Output: 1
Explanation:
There is only one car, hence there is only one fleet.
Example 3:
Input: target = 100, position = [0,2,4], speed = [4,2,1]
Output: 1
Explanation:
• The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet,
meeting each other at 4. The car starting at 4 (speed 1) travels to 5.
• Then, the fleet at 4 (speed 2) and the car at position 5 (speed 1)
become one fleet, meeting each other at 6. The fleet moves at speed 1
until it reaches target.
Constraints:
• n == position.length == speed.length
• 1 <= n <= 10^5
• 0 < target <= 10^6
• 0 <= position[i] < target
• All the values of position are unique.
• 0 < speed[i] <= 10^6
"""
class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
stack = []
for pos, spd in sorted(zip(position, speed), reverse=True):
time = (target - pos) / spd
if not stack or time > stack[-1]:
stack.append(time)
return len(stack)
@@ -0,0 +1,80 @@
/*
* 875. Koko Eating Bananas
* Difficulty: Medium
* https://leetcode.com/problems/koko-eating-bananas/
*
* ──────────────────────────────────────────────────
*
* Koko loves to eat bananas. There are n piles of bananas, the i^th
* pile has piles[i] bananas. The guards have gone and will come back in
* h hours.
*
* Koko can decide her bananas-per-hour eating speed of k. Each hour,
* she chooses some pile of bananas and eats k bananas from that pile. If
* the pile has less than k bananas, she eats all of them instead and
* will not eat any more bananas during this hour.
*
* Koko likes to eat slowly but still wants to finish eating all the
* bananas before the guards return.
*
* Return the minimum integer k such that she can eat all the bananas
* within h hours.
*
*
*
* Example 1:
*
* Input: piles = [3,6,7,11], h = 8
* Output: 4
*
* Example 2:
*
* Input: piles = [30,11,23,4,20], h = 5
* Output: 30
*
* Example 3:
*
* Input: piles = [30,11,23,4,20], h = 6
* Output: 23
*
*
*
* Constraints:
*
* • 1 <= piles.length <= 10^4
*
* • piles.length <= h <= 10^9
*
* • 1 <= piles[i] <= 10^9
*/
/**
* @param {number[]} piles
* @param {number} h
* @return {number}
*/
var minEatingSpeed = function(piles, h) {
// Function to determine if K works for the H
function kWorks(k){
let hours = 0;
for (let p of piles){
hours += Math.ceil(p/k)
}
return hours <= h;
}
// Setup Binary Search
let l = 1;
let r = Math.max(...piles);
// Find the K value which works for H and consumes all bananas
while (l < r){
const mid = Math.floor((l + r) / 2);
if (kWorks(mid)){
r = mid;
}else{
l = mid + 1;
}
}
return l;
};
@@ -0,0 +1,56 @@
"""
3. Longest Substring Without Repeating Characters
Difficulty: Medium
https://leetcode.com/problems/longest-substring-without-repeating-characters/
──────────────────────────────────────────────────
Given a string s, find the length of the longest substring without
duplicate characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3. Note that
"bca" and "cab" are also correct answers.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence
and not a substring.
Constraints:
• 0 <= s.length <= 10^5
• s consists of English letters, digits, symbols and spaces.
"""
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
left = 0
ans = 0
window = set()
for right, c in enumerate(s):
while c in window:
window.remove(s[left])
left += 1
window.add(c)
ans = max(ans, right - left + 1)
return ans
@@ -0,0 +1,60 @@
"""
424. Longest Repeating Character Replacement
Difficulty: Medium
https://leetcode.com/problems/longest-repeating-character-replacement/
──────────────────────────────────────────────────
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.
Example 1:
Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input: s = "AABABBA", k = 1
Output: 4
Explanation: Replace the one 'A' in the middle with 'B' and form
"AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
There may exists other ways to achieve this answer too.
Constraints:
• 1 <= s.length <= 10^5
• s consists of only uppercase English letters.
• 0 <= k <= s.length
"""
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
count = {}
res = 0
l = 0
maxF = 0
for r, c in enumerate(s):
count[c] = 1 + count.get(c, 0)
maxF = max(maxF, count[c])
while (r - l + 1) - maxF > k:
count[s[l]] -= 1
l += 1
res = max(res, r - l + 1)
return res
@@ -0,0 +1,64 @@
/*
* 451. Sort Characters By Frequency
* Difficulty: Medium
* https://leetcode.com/problems/sort-characters-by-frequency/
*
* ──────────────────────────────────────────────────
*
* Given a string s, sort it in decreasing order based on the frequency
* of the characters. The frequency of a character is the number of times
* it appears in the string.
*
* Return the sorted string. If there are multiple answers, return any
* of them.
*
*
*
* Example 1:
*
* Input: s = "tree"
* Output: "eert"
* Explanation: 'e' appears twice while 'r' and 't' both appear once.
* So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also
* a valid answer.
*
* Example 2:
*
* Input: s = "cccaaa"
* Output: "aaaccc"
* Explanation: Both 'c' and 'a' appear three times, so both "cccaaa"
* and "aaaccc" are valid answers.
* Note that "cacaca" is incorrect, as the same characters must be
* together.
*
* Example 3:
*
* Input: s = "Aabb"
* Output: "bbAa"
* Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
* Note that 'A' and 'a' are treated as two different characters.
*
*
*
* Constraints:
*
* • 1 <= s.length <= 5 * 10^5
*
* • s consists of uppercase and lowercase English letters and digits.
*/
/**
* @param {string} s
* @return {string}
*/
var frequencySort = function (s) {
// count the frequency of each character
const freq = {};
for (let c of s) freq[c] = (freq[c] || 0) + 1;
// sort the characters by frequency
return s
.split("")
.sort((a, b) => freq[b] - freq[a] || a.localeCompare(b))
.join("");
};
@@ -0,0 +1,58 @@
"""
567. Permutation in String
Difficulty: Medium
https://leetcode.com/problems/permutation-in-string/
──────────────────────────────────────────────────
Given two strings s1 and s2, return true if s2 contains a permutation
of s1, or false otherwise.
In other words, return true if one of s1's permutations is the
substring of s2.
Example 1:
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
Constraints:
• 1 <= s1.length, s2.length <= 10^4
• s1 and s2 consist of lowercase English letters.
"""
from collections import Counter
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
k = len(s1)
if k > len(s2):
return False
need = Counter(s1)
window = Counter()
for right, c in enumerate(s2):
window[c] += 1
if right >= k:
left_char = s2[right - k]
window[left_char] -= 1
if window[left_char] == 0:
del window[left_char]
if window == need:
return True
return False
+86
View File
@@ -0,0 +1,86 @@
"""
155. Min Stack
Difficulty: Medium
https://leetcode.com/problems/min-stack/
──────────────────────────────────────────────────
Design a stack that supports push, pop, top, and retrieving the
minimum element in constant time.
Implement the MinStack class:
• MinStack() initializes the stack object.
• void push(int value) pushes the element value onto the stack.
• void pop() removes the element on the top of the stack.
• int top() gets the top element of the stack.
• int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each
function.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
• -2^31 <= val <= 2^31 - 1
• Methods pop, top and getMin operations will always be called on
non-empty stacks.
• At most 3 * 10^4 calls will be made to push, pop, top, and getMin.
"""
class MinStack:
def __init__(self):
self.stack = []
self.minStack = []
def push(self, value: int) -> None:
self.stack.append(value)
value = min(value, self.minStack[-1] if self.minStack else value)
self.minStack.append(value)
def pop(self) -> None:
self.stack.pop()
self.minStack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.minStack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(value)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()