mirror of
https://github.com/prdlk/leetcode.git
synced 2026-09-16 23:16:26 +00:00
refactor(work): restructure solution directories with bucket level and add .gitkeep placeholders
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
1. Two Sum
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/two-sum/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
You are given an array of integers nums and an integer target, return
|
||||
indices of the two numbers such that they add up to target.
|
||||
|
||||
You may assume that each input would have exactly one solution, and
|
||||
you may not use the same element twice.
|
||||
|
||||
You can return the answer in any order.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: nums = [2,7,11,15], target = 9
|
||||
Output: [0,1]
|
||||
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: nums = [3,2,4], target = 6
|
||||
Output: [1,2]
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: nums = [3,3], target = 6
|
||||
Output: [0,1]
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 2 <= nums.length <= 10^4
|
||||
|
||||
• -10^9 <= nums[i] <= 10^9
|
||||
|
||||
• -10^9 <= target <= 10^9
|
||||
|
||||
• Only one valid answer exists.
|
||||
|
||||
|
||||
|
||||
Follow-up: Can you come up with an algorithm that is less than O(n^2)
|
||||
time complexity?
|
||||
"""
|
||||
|
||||
class Solution:
|
||||
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
||||
seen = {}
|
||||
for i, num in enumerate(nums):
|
||||
complement = target - num
|
||||
if complement in seen:
|
||||
return [seen[complement], i]
|
||||
seen[num] = i
|
||||
return []
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
121. Best Time to Buy and Sell Stock
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
You are given an array prices where prices[i] is the price of a given
|
||||
stock on the i^th day.
|
||||
|
||||
You want to maximize your profit by choosing a single day to buy one
|
||||
stock and choosing a different day in the future to sell that stock.
|
||||
|
||||
Return the maximum profit you can achieve from this transaction. If
|
||||
you cannot achieve any profit, return 0.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: prices = [7,1,5,3,6,4]
|
||||
Output: 5
|
||||
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6),
|
||||
profit = 6-1 = 5.
|
||||
Note that buying on day 2 and selling on day 1 is not allowed because
|
||||
you must buy before you sell.
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: prices = [7,6,4,3,1]
|
||||
Output: 0
|
||||
Explanation: In this case, no transactions are done and the max
|
||||
profit = 0.
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 1 <= prices.length <= 10^5
|
||||
|
||||
• 0 <= prices[i] <= 10^4
|
||||
"""
|
||||
|
||||
class Solution:
|
||||
def maxProfit(self, prices: List[int]) -> int:
|
||||
left = min(prices)
|
||||
for right in range(len(prices)):
|
||||
while curr > left:
|
||||
curr -= prices[left]
|
||||
left += 1
|
||||
ans = max(ans, curr)
|
||||
return ans
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 1365. How Many Numbers Are Smaller Than the Current Number
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given the array nums, for each nums[i] find out how many numbers in
|
||||
* the array are smaller than it. That is, for each nums[i] you have to
|
||||
* count the number of valid j's such that j != i and nums[j] < nums[i].
|
||||
*
|
||||
* Return the answer in an array.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [8,1,2,2,3]
|
||||
* Output: [4,0,1,1,3]
|
||||
* Explanation:
|
||||
* For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and
|
||||
* 3).
|
||||
* For nums[1]=1 does not exist any smaller number than it.
|
||||
* For nums[2]=2 there exist one smaller number than it (1).
|
||||
* For nums[3]=2 there exist one smaller number than it (1).
|
||||
* For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [6,5,4,8]
|
||||
* Output: [2,1,0,3]
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: nums = [7,7,7,7]
|
||||
* Output: [0,0,0,0]
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 2 <= nums.length <= 500
|
||||
*
|
||||
* • 0 <= nums[i] <= 100
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number[]}
|
||||
*/
|
||||
|
||||
var smallerNumbersThanCurrent = function (nums) {
|
||||
// Step 1: Begin by initializing a [Frequency Map]()
|
||||
const freq = {};
|
||||
for (let n of nums) freq[n] = (freq[n] || 0) + 1;
|
||||
|
||||
// Step 2: Sort the numbers by ascending order
|
||||
const sorted = Object.keys(freq).sort((a, b) => a - b);
|
||||
|
||||
// Step 3: Init a count of numbers smaller than the active number
|
||||
let count = 0;
|
||||
|
||||
// Step 4: Init a map to track number of values smaller for each number
|
||||
const smaller = {};
|
||||
|
||||
// Step 5: Iterate over the sorted list
|
||||
for (let num of sorted) {
|
||||
// Set count for active number
|
||||
smaller[num] = count;
|
||||
|
||||
// Update the count by frequency
|
||||
count += freq[num];
|
||||
}
|
||||
|
||||
// Step 6: Use original list and find number of smaller values than it
|
||||
return nums.map((n) => smaller[n]);
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* 1413. Minimum Value to Get Positive Step by Step Sum
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an array of integers nums, you start with an initial positive
|
||||
* value startValue.
|
||||
*
|
||||
* In each iteration, you calculate the step by step sum of startValue
|
||||
* plus elements in nums (from left to right).
|
||||
*
|
||||
* Return the minimum positive value of startValue such that the step by
|
||||
* step sum is never less than 1.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [-3,2,-3,4,2]
|
||||
* Output: 5
|
||||
* Explanation: If you choose startValue = 4, in the third iteration
|
||||
* your step by step sum is less than 1.
|
||||
* step by step sum
|
||||
* startValue = 4 | startValue = 5 | nums
|
||||
* (4 -3 ) = 1 | (5 -3 ) = 2 | -3
|
||||
* (1 +2 ) = 3 | (2 +2 ) = 4 | 2
|
||||
* (3 -3 ) = 0 | (4 -3 ) = 1 | -3
|
||||
* (0 +4 ) = 4 | (1 +4 ) = 5 | 4
|
||||
* (4 +2 ) = 6 | (5 +2 ) = 7 | 2
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [1,2]
|
||||
* Output: 1
|
||||
* Explanation: Minimum start value should be positive.
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: nums = [1,-2,-3]
|
||||
* Output: 5
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 100
|
||||
*
|
||||
* • -100 <= nums[i] <= 100
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number}
|
||||
*/
|
||||
var minStartValue = function(nums) {
|
||||
let prefix = [nums[0]];
|
||||
// Make prefix sum start at 1 after initializing seed value
|
||||
for (let i = 1; i < nums.length; i++){
|
||||
prefix.push(prefix[i - 1] + nums[i]);
|
||||
}
|
||||
|
||||
let min = Math.min(...prefix);
|
||||
return Math.max(1, 1 - min);
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* 1426. Counting Elements
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/counting-elements/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an integer array arr, count how many elements x there are, such
|
||||
* that x + 1 is also in arr. If there are duplicates in arr, count them
|
||||
* separately.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: arr = [1,2,3]
|
||||
* Output: 2
|
||||
* Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: arr = [1,1,3,3,5,5,7,7]
|
||||
* Output: 0
|
||||
* Explanation: No numbers are counted, cause there is no 2, 4, 6, or 8
|
||||
* in arr.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= arr.length <= 1000
|
||||
*
|
||||
* • 0 <= arr[i] <= 1000
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} arr
|
||||
* @return {number}
|
||||
*/
|
||||
var countElements = function(arr) {
|
||||
let arrSet = new Set(arr);
|
||||
let count = 0;
|
||||
|
||||
for (let n of arr) {
|
||||
let sum = n + 1;
|
||||
if (arrSet.has(sum)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 1480. Running Sum of 1d Array
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/running-sum-of-1d-array/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an array nums. We define a running sum of an array as
|
||||
* runningSum[i] = sum(nums[0]…nums[i]).
|
||||
*
|
||||
* Return the running sum of nums.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [1,2,3,4]
|
||||
* Output: [1,3,6,10]
|
||||
* Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3,
|
||||
* 1+2+3+4].
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [1,1,1,1,1]
|
||||
* Output: [1,2,3,4,5]
|
||||
* Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1,
|
||||
* 1+1+1+1, 1+1+1+1+1].
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: nums = [3,1,2,10,1]
|
||||
* Output: [3,4,6,16,17]
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 1000
|
||||
*
|
||||
* • -10^6 <= nums[i] <= 10^6
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number[]}
|
||||
*/
|
||||
var runningSum = function(nums) {
|
||||
let prefix = [nums[0]];
|
||||
for (let i = 1; i < nums.length; i++){
|
||||
prefix.push(prefix[i - 1] + nums[i]);
|
||||
}
|
||||
return prefix;
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 1636. Sort Array by Increasing Frequency
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/sort-array-by-increasing-frequency/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an array of integers nums, sort the array in increasing order
|
||||
* based on the frequency of the values. If multiple values have the same
|
||||
* frequency, sort them in decreasing order.
|
||||
*
|
||||
* Return the sorted array.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [1,1,2,2,2,3]
|
||||
* Output: [3,1,1,2,2,2]
|
||||
* Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and
|
||||
* '2' has a frequency of 3.
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [2,3,1,3,2]
|
||||
* Output: [1,3,3,2,2]
|
||||
* Explanation: '2' and '3' both have a frequency of 2, so they are
|
||||
* sorted in decreasing order.
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: nums = [-1,1,-6,4,5,-6,1,4,1]
|
||||
* Output: [5,-1,4,4,-6,-6,1,1,1]
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 100
|
||||
*
|
||||
* • -100 <= nums[i] <= 100
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number[]}
|
||||
*/
|
||||
var frequencySort = function (nums) {
|
||||
const freq = {};
|
||||
for (let n of nums) freq[n] = (freq[n] || 0) + 1;
|
||||
return nums.sort((a, b) => freq[a] - freq[b] || b - a);
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 217. Contains Duplicate
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/contains-duplicate/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an integer array nums, return true if any value appears at
|
||||
* least twice in the array, and return false if every element is
|
||||
* distinct.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [1,2,3,1]
|
||||
*
|
||||
* Output: true
|
||||
*
|
||||
* Explanation:
|
||||
*
|
||||
* The element 1 occurs at the indices 0 and 3.
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [1,2,3,4]
|
||||
*
|
||||
* Output: false
|
||||
*
|
||||
* Explanation:
|
||||
*
|
||||
* All elements are distinct.
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: nums = [1,1,1,3,3,4,3,2,4,2]
|
||||
*
|
||||
* Output: true
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 10^5
|
||||
*
|
||||
* • -10^9 <= nums[i] <= 10^9
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {boolean}
|
||||
*/
|
||||
var containsDuplicate = function(nums) {
|
||||
const freq = {};
|
||||
for (let n of nums) {
|
||||
freq[n] = (freq[n] || 0) + 1;
|
||||
if (freq[n] >= 2) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* 268. Missing Number
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/missing-number/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an array nums containing n distinct numbers in the range [0,
|
||||
* n], return the only number in the range that is missing from the
|
||||
* array.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [3,0,1]
|
||||
*
|
||||
* Output: 2
|
||||
*
|
||||
* Explanation:
|
||||
*
|
||||
* n = 3 since there are 3 numbers, so all numbers are in the range
|
||||
* [0,3]. 2 is the missing number in the range since it does not appear
|
||||
* in nums.
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [0,1]
|
||||
*
|
||||
* Output: 2
|
||||
*
|
||||
* Explanation:
|
||||
*
|
||||
* n = 2 since there are 2 numbers, so all numbers are in the range
|
||||
* [0,2]. 2 is the missing number in the range since it does not appear
|
||||
* in nums.
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: nums = [9,6,4,2,3,5,7,0,1]
|
||||
*
|
||||
* Output: 8
|
||||
*
|
||||
* Explanation:
|
||||
*
|
||||
* n = 9 since there are 9 numbers, so all numbers are in the range
|
||||
* [0,9]. 8 is the missing number in the range since it does not appear
|
||||
* in nums.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • n == nums.length
|
||||
*
|
||||
* • 1 <= n <= 10^4
|
||||
*
|
||||
* • 0 <= nums[i] <= n
|
||||
*
|
||||
* • All the numbers of nums are unique.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Follow up: Could you implement a solution using only O(1) extra space
|
||||
* complexity and O(n) runtime complexity?
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number}
|
||||
*/
|
||||
var missingNumber = function(nums) {
|
||||
const numSet = new Set(nums);
|
||||
const expectedCount = nums.length + 1;
|
||||
|
||||
for (let i = 0; i < expectedCount; i++){
|
||||
if(!numSet.has(i)){
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 303. Range Sum Query - Immutable
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/range-sum-query-immutable/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an integer array nums, handle multiple queries of the following
|
||||
* type:
|
||||
*
|
||||
* • Calculate the sum of the elements of nums between indices left and
|
||||
* right inclusive where left <= right.
|
||||
*
|
||||
* Implement the NumArray class:
|
||||
*
|
||||
* • NumArray(int[] nums) Initializes the object with the integer array
|
||||
* nums.
|
||||
*
|
||||
* • int sumRange(int left, int right) Returns the sum of the elements
|
||||
* of nums between indices left and right inclusive (i.e. nums[left] +
|
||||
* nums[left + 1] + ... + nums[right]).
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input
|
||||
* ["NumArray", "sumRange", "sumRange", "sumRange"]
|
||||
* [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
|
||||
* Output
|
||||
* [null, 1, -1, -3]
|
||||
*
|
||||
* Explanation
|
||||
* NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
|
||||
* numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
|
||||
* numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
|
||||
* numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 10^4
|
||||
*
|
||||
* • -10^5 <= nums[i] <= 10^5
|
||||
*
|
||||
* • 0 <= left <= right < nums.length
|
||||
*
|
||||
* • At most 10^4 calls will be made to sumRange.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
*/
|
||||
class NumArray {
|
||||
constructor(nums) {
|
||||
this.prefix = [0];
|
||||
for (let n of nums){
|
||||
this.prefix.push(this.prefix[this.prefix.length - 1] + n);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param {number} left
|
||||
* @param {number} right
|
||||
* @return {number}
|
||||
*/
|
||||
sumRange(left, right) {
|
||||
return this.prefix[right + 1] - this.prefix[left];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Your NumArray object will be instantiated and called as such:
|
||||
* var obj = new NumArray(nums)
|
||||
* var param_1 = obj.sumRange(left,right)
|
||||
*/
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
35. Search Insert Position
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/search-insert-position/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given a sorted array of distinct integers and a target value, return
|
||||
the index if the target is found. If not, return the index where it
|
||||
would be if it were inserted in order.
|
||||
|
||||
You must write an algorithm with O(log n) runtime complexity.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: nums = [1,3,5,6], target = 5
|
||||
Output: 2
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: nums = [1,3,5,6], target = 2
|
||||
Output: 1
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: nums = [1,3,5,6], target = 7
|
||||
Output: 4
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 1 <= nums.length <= 10^4
|
||||
|
||||
• -10^4 <= nums[i] <= 10^4
|
||||
|
||||
• nums contains distinct values sorted in ascending order.
|
||||
|
||||
• -10^4 <= target <= 10^4
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def searchInsert(self, nums: List[int], target: int) -> int:
|
||||
l, r = 0, len(nums) - 1
|
||||
|
||||
while l <= r:
|
||||
m = (l + r) // 2
|
||||
if nums[m] == target:
|
||||
return m
|
||||
elif nums[m] < target:
|
||||
l = m + 1
|
||||
elif nums[m] > target:
|
||||
r = m - 1
|
||||
|
||||
return (l + r) // 2 + 1
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* 704. Binary Search
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/binary-search/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an array of integers nums which is sorted in ascending order,
|
||||
* and an integer target, write a function to search target in nums. If
|
||||
* target exists, then return its index. Otherwise, return -1.
|
||||
*
|
||||
* You must write an algorithm with O(log n) runtime complexity.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [-1,0,3,5,9,12], target = 9
|
||||
* Output: 4
|
||||
* Explanation: 9 exists in nums and its index is 4
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [-1,0,3,5,9,12], target = 2
|
||||
* Output: -1
|
||||
* Explanation: 2 does not exist in nums so return -1
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 10^4
|
||||
*
|
||||
* • -10^4 < nums[i], target < 10^4
|
||||
*
|
||||
* • All the integers in nums are unique.
|
||||
*
|
||||
* • nums is sorted in ascending order.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @param {number} target
|
||||
* @return {number}
|
||||
*/
|
||||
var search = function(nums, target) {
|
||||
let left = 0;
|
||||
let right = nums.length - 1;
|
||||
|
||||
while(left <= right) {
|
||||
const mid = left + Math.floor((right - left) / 2);
|
||||
if (nums[mid] === target) {
|
||||
return mid;
|
||||
} else if(nums[mid] < target){
|
||||
left = mid + 1;
|
||||
} else if (nums[mid] > target) {
|
||||
right = mid - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 977. Squares of a Sorted Array
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/squares-of-a-sorted-array/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an integer array nums sorted in non-decreasing order, return an
|
||||
* array of the squares of each number sorted in non-decreasing order.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [-4,-1,0,3,10]
|
||||
* Output: [0,1,9,16,100]
|
||||
* Explanation: After squaring, the array becomes [16,1,0,9,100].
|
||||
* After sorting, it becomes [0,1,9,16,100].
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [-7,-3,2,3,11]
|
||||
* Output: [4,9,9,49,121]
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 10^4
|
||||
*
|
||||
* • -10^4 <= nums[i] <= 10^4
|
||||
*
|
||||
* • nums is sorted in non-decreasing order.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Follow up: Squaring each element and sorting the new array is very
|
||||
* trivial, could you find an O(n) solution using a different approach?
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number[]}
|
||||
*/
|
||||
var sortedSquares = function(nums) {
|
||||
let n = nums.length;
|
||||
let ans = new Array(nums.length);
|
||||
let left = 0, right = nums.length - 1;
|
||||
|
||||
for (let i = n -1; i >= 0; i--){
|
||||
let square;
|
||||
if(Math.abs(nums[left]) < Math.abs(nums[right])){
|
||||
square = nums[right];
|
||||
right--;
|
||||
}else{
|
||||
square = nums[left];
|
||||
left++;
|
||||
}
|
||||
ans[i] = square*square;
|
||||
}
|
||||
return ans;
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* 1832. Check if the Sentence Is Pangram
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/check-if-the-sentence-is-pangram/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* A pangram is a sentence where every letter of the English alphabet
|
||||
* appears at least once.
|
||||
*
|
||||
* Given a string sentence containing only lowercase English letters,
|
||||
* return true if sentence is a pangram, or false otherwise.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
|
||||
* Output: true
|
||||
* Explanation: sentence contains at least one of every letter of the
|
||||
* English alphabet.
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: sentence = "leetcode"
|
||||
* Output: false
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= sentence.length <= 1000
|
||||
*
|
||||
* • sentence consists of lowercase English letters.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} sentence
|
||||
* @return {boolean}
|
||||
*/
|
||||
var checkIfPangram = function(sentence) {
|
||||
const freq = {};
|
||||
for (let c of sentence) freq[c] = (freq[c] || 0) + 1;
|
||||
|
||||
if (Object.keys(freq).length === 26){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* 242. Valid Anagram
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/valid-anagram/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given two strings s and t, return true if t is an anagram of s, and
|
||||
* false otherwise.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: s = "anagram", t = "nagaram"
|
||||
*
|
||||
* Output: true
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: s = "rat", t = "car"
|
||||
*
|
||||
* Output: false
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= s.length, t.length <= 5 * 10^4
|
||||
*
|
||||
* • s and t consist of lowercase English letters.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Follow up: What if the inputs contain Unicode characters? How would
|
||||
* you adapt your solution to such a case?
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} s
|
||||
* @param {string} t
|
||||
* @return {boolean}
|
||||
*/
|
||||
var isAnagram = function(s, t) {
|
||||
let freq = {};
|
||||
for (let c of s) freq[c] = (freq[c] || 0) + 1;
|
||||
|
||||
for (let c of t) {
|
||||
if(!freq[c] || freq[c] === 0){
|
||||
return false;
|
||||
}
|
||||
freq[c] = freq[c] - 1;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* 387. First Unique Character in a String
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/first-unique-character-in-a-string/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given a string s, find the first non-repeating character in it and
|
||||
* return its index. If it does not exist, return -1.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: s = "leetcode"
|
||||
*
|
||||
* Output: 0
|
||||
*
|
||||
* Explanation:
|
||||
*
|
||||
* The character 'l' at index 0 is the first character that does not
|
||||
* occur at any other index.
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: s = "loveleetcode"
|
||||
*
|
||||
* Output: 2
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: s = "aabb"
|
||||
*
|
||||
* Output: -1
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= s.length <= 10^5
|
||||
*
|
||||
* • s consists of only lowercase English letters.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} s
|
||||
* @return {number}
|
||||
*/
|
||||
var firstUniqChar = function (s) {
|
||||
const freq = {};
|
||||
for (let c of s) freq[c] = (freq[c] || 0) + 1;
|
||||
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
if (freq[s[i]] === 1) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
20. Valid Parentheses
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/valid-parentheses/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given a string s containing just the characters '(', ')', '{', '}',
|
||||
'[' and ']', determine if the input string is valid.
|
||||
|
||||
An input string is valid if:
|
||||
|
||||
• Open brackets must be closed by the same type of brackets.
|
||||
|
||||
• Open brackets must be closed in the correct order.
|
||||
|
||||
• Every close bracket has a corresponding open bracket of the same
|
||||
type.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: s = "()"
|
||||
|
||||
Output: true
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: s = "()[]{}"
|
||||
|
||||
Output: true
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: s = "(]"
|
||||
|
||||
Output: false
|
||||
|
||||
Example 4:
|
||||
|
||||
Input: s = "([])"
|
||||
|
||||
Output: true
|
||||
|
||||
Example 5:
|
||||
|
||||
Input: s = "([)]"
|
||||
|
||||
Output: false
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 1 <= s.length <= 10^4
|
||||
|
||||
• s consists of parentheses only '()[]{}'.
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def isValid(self, s: str) -> bool:
|
||||
stack = []
|
||||
pairs = {")": "(", "]": "[", "}": "{"}
|
||||
|
||||
for c in s:
|
||||
if c in pairs:
|
||||
if stack and pairs[c] == stack[-1]:
|
||||
stack.pop()
|
||||
else:
|
||||
return False
|
||||
else:
|
||||
stack.append(c)
|
||||
|
||||
return True if not stack else False
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* 125. Valid Palindrome
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/valid-palindrome/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* A phrase is a palindrome if, after converting all uppercase letters
|
||||
* into lowercase letters and removing all non-alphanumeric characters,
|
||||
* it reads the same forward and backward. Alphanumeric characters
|
||||
* include letters and numbers.
|
||||
*
|
||||
* Given a string s, return true if it is a palindrome, or false
|
||||
* otherwise.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: s = "A man, a plan, a canal: Panama"
|
||||
* Output: true
|
||||
* Explanation: "amanaplanacanalpanama" is a palindrome.
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: s = "race a car"
|
||||
* Output: false
|
||||
* Explanation: "raceacar" is not a palindrome.
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: s = " "
|
||||
* Output: true
|
||||
* Explanation: s is an empty string "" after removing non-alphanumeric
|
||||
* characters.
|
||||
* Since an empty string reads the same forward and backward, it is a
|
||||
* palindrome.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= s.length <= 2 * 10^5
|
||||
*
|
||||
* • s consists only of printable ASCII characters.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} s
|
||||
* @return {boolean}
|
||||
*/
|
||||
var isPalindrome = function(s) {
|
||||
let normal = s.replace(/[^a-zA-Z0-9]/g, "").toLowerCase()
|
||||
let i = 0, j = normal.length - 1;
|
||||
|
||||
while (i < j) {
|
||||
if(normal[i] !== normal[j]) {
|
||||
return false;
|
||||
}
|
||||
i++;
|
||||
j--;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* 344. Reverse String
|
||||
* Difficulty: Easy
|
||||
* https://leetcode.com/problems/reverse-string/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Write a function that reverses a string. The input string is given as
|
||||
* an array of characters s.
|
||||
*
|
||||
* You must do this by modifying the input array in-place with O(1)
|
||||
* extra memory.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: s = ["h","e","l","l","o"]
|
||||
* Output: ["o","l","l","e","h"]
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: s = ["H","a","n","n","a","h"]
|
||||
* Output: ["h","a","n","n","a","H"]
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= s.length <= 10^5
|
||||
*
|
||||
* • s[i] is a printable ascii character.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {character[]} s
|
||||
* @return {void} Do not return anything, modify s in-place instead.
|
||||
*/
|
||||
var reverseString = function(s) {
|
||||
let i = 0;
|
||||
let j = s.length - 1;
|
||||
|
||||
while (i < j) {
|
||||
[s[i], s[j]] = [s[j], s[i]];
|
||||
j--;
|
||||
i++;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
392. Is Subsequence
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/is-subsequence/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given two strings s and t, return true if s is a subsequence of t, or
|
||||
false otherwise.
|
||||
|
||||
A subsequence of a string is a new string that is formed from the
|
||||
original string by deleting some (can be none) of the characters
|
||||
without disturbing the relative positions of the remaining characters.
|
||||
(i.e., "ace" is a subsequence of "abcde" while "aec" is not).
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: s = "abc", t = "ahbgdc"
|
||||
Output: true
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: s = "axc", t = "ahbgdc"
|
||||
Output: false
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 0 <= s.length <= 100
|
||||
|
||||
• 0 <= t.length <= 10^4
|
||||
|
||||
• s and t consist only of lowercase English letters.
|
||||
|
||||
|
||||
|
||||
Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk
|
||||
where k >= 10^9, and you want to check one by one to see if t has its
|
||||
subsequence. In this scenario, how would you change your code?
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def isSubsequence(self, s: str, t: str) -> bool:
|
||||
if len(s) > len(t):
|
||||
return False
|
||||
|
||||
i, j = 0, 0
|
||||
while i < len(s) and j < len(t):
|
||||
if s[i] == t[j]:
|
||||
i += 1
|
||||
j += 1
|
||||
|
||||
return i == len(s)
|
||||
@@ -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
|
||||
@@ -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);
|
||||
};
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user