-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from dexterpuru/master
pulling from original
- Loading branch information
Showing
12 changed files
with
315 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
#### Leetcode Link: | ||
|
||
https://leetcode.com/problems/subarray-product-less-than-k/ | ||
|
||
### Problem Statement | ||
|
||
Your are given an array of positive integers nums. | ||
|
||
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k. | ||
|
||
**Example 1:** | ||
``` | ||
Input: nums = [10, 5, 2, 6], k = 100 | ||
Output: 8 | ||
Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]. | ||
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. | ||
``` | ||
|
||
**Note:** | ||
``` | ||
0 < nums.length <= 50000. | ||
0 < nums[i] < 1000. | ||
0 <= k < 10^6 | ||
``` | ||
|
||
### Approach | ||
|
||
We can apply sliding window type of approach to solve this problem. Where we create a virtual window that contains the range of values that whose product are less then a given `k`. Every time when we slide the window to one-step to the right, we check and stabilize the table by shifting the left-side border (if necessary). Summary of range size in every step gives us expected result. | ||
|
||
- initilize left and right borders of the window | ||
- `product` initialized as 1 (thats what usually used for production aggregation) | ||
- `productCount` initialized as a 0 (this is where we aggregate summary of possible variations) | ||
- run the cycle for the whole array | ||
- multiply the next coming value to the `product` aggregator | ||
- if the `product` aggregator is over the given `k` limit, then start subtracting left-most elements of the window (by shifting the left border to the right) | ||
- aggregate current is of the window | ||
|
||
**Time Complexity: O(N)**, where N is the number of elements in the array. | ||
|
||
**Space Complexity: O(1)**, only operational variables are used. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
class Solution { | ||
public int numSubarrayProductLessThanK(int[] nums, int k) { | ||
int left = 0, right = 0; | ||
int product = 1; | ||
int prodCount = 0; | ||
while (right < nums.length) { | ||
product *= nums[right]; | ||
while (left <= right && product >= k) { | ||
product = product / nums[left]; | ||
left++; | ||
} | ||
|
||
prodCount += right - left + 1; | ||
right++; | ||
} | ||
return prodCount; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
#### Leetcode Link: | ||
|
||
> https://leetcode.com/problems/number-of-recent-calls | ||
### Problem Statement | ||
|
||
> | ||
> You have a RecentCounter class which counts the number of recent requests within a certain time frame. | ||
> | ||
> Implement the RecentCounter class: | ||
> | ||
> - RecentCounter() Initializes the counter with zero recent requests. | ||
> - int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t]. | ||
> | ||
> It is guaranteed that every call to ping uses a strictly larger value of t than the previous call. | ||
> | ||
> | ||
> Example 1: | ||
> | ||
> **Input** | ||
> ``` | ||
> ["RecentCounter", "ping", "ping", "ping", "ping"] | ||
> [[], [1], [100], [3001], [3002]] | ||
> ``` | ||
> **Output** | ||
> ``` | ||
> [null, 1, 2, 3, 3] | ||
> ``` | ||
> **Explanation** | ||
> ``` | ||
> RecentCounter recentCounter = new RecentCounter(); | ||
> recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 | ||
> recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2 | ||
> recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3 | ||
> recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3 | ||
> ``` | ||
> | ||
> | ||
> **Constraints:** | ||
> | ||
> - 1 <= t <= 10^4 | ||
> - Each test case will call ping with strictly increasing values of t. | ||
> - At most 10^4 calls will be made to ping. | ||
> | ||
### Approach | ||
|
||
There are multiple solutions for this problem. First I have solved it using ArrayList, since the constraints are not that high. But if we consider total optimization (consider not only about speed but also space) then usage of LinkedList is more reasonable. | ||
|
||
### Pseudo-code | ||
|
||
> | ||
> - Initialize the LinkedList | ||
> - Every time when the ping method is called we add the `t` value from the right side to the linked-list, | ||
> - check the left-most value for being bigger then `t-3000` | ||
> - If the left-most value is less than `t-3000` then remove it from the linked list (do it in a cycle) | ||
> | ||
|
||
|
||
**Time Complexity: O(M)**, We have a constant time complexity, since every time when we do a ping we just add and remove values to right-most and left-most positions. We have no iteration over the list. Worst case we would remove 3000 elements from the left which still stays a constant. | ||
|
||
**Space Complexity: O(M)**, M is a maximum size of the linked list which is 3000. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
|
||
class RecentCounter { | ||
LinkedList<Integer> times; | ||
public RecentCounter() { | ||
times = new LinkedList<Integer>(); | ||
} | ||
|
||
public int ping(int t) { | ||
times.add(t); | ||
while (times.getFirst() < t-3000) { | ||
times.removeFirst(); | ||
} | ||
|
||
return times.size(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
57 changes: 57 additions & 0 deletions
57
String/Longest Substring without repeating characters/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
#### LeetCode Url: | ||
|
||
> https://leetcode.com/problems/longest-substring-without-repeating-characters/ | ||
### Problem Statement: | ||
|
||
Given a string s, find the length of the longest substring without repeating characters. | ||
|
||
**Example 1:** | ||
|
||
> **Input:** s = "abcabcbb" | ||
> **Output:** 3 | ||
> **Explanation:** The answer is "abc", with the length of 3. | ||
**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. | ||
**Example 4:** | ||
|
||
> **Input:** s = "" | ||
> **Output:** 0 | ||
**Constraints:** | ||
|
||
> 0 <= s.length <= 5 \* 10<sup>4</sup> | ||
> s consists of English letters, digits, symbols and spaces. | ||
### Solution: | ||
|
||
**Intuition:** | ||
|
||
> Check all the substring one by one to see if it has no duplicate character. | ||
## Sliding Window Approach | ||
|
||
**Algorithm:** | ||
|
||
> By using HashSet as a sliding window, checking if a character in the current can be done in O(1). | ||
> A sliding window is an abstract concept commonly used in array/string problems. A window is a range of elements in the array/string which usually defined by the start and end indices, i.e. [i, j) (left-closed, right-open). A sliding window is a window "slides" its two boundaries to the certain direction. For example, if we slide [i, j) to the right by 1 element, then it becomes [i+1, j+1) (left-closed, right-open). | ||
> Back to our problem. We use HashSet to store the characters in current window [i, j) (j = i initially). Then we slide the index j to the right. If it is not in the HashSet, we slide j further. Doing so until s[j] is already in the HashSet. At this point, we found the maximum size of substrings without duplicate characters start with index i. If we do this for all i, we get our answer. | ||
**Complexity Analysis:** | ||
|
||
> **Time complexity:** O(2n) = O(n). In the worst case each character will be visited twice by i and j. | ||
> **Space complexity:** O(min(m, n)). We need O(k) space for the sliding window, where k is the size of the Set. The size of the Set is upper bounded by the size of the string n and the size of the charset/alphabet m. |
19 changes: 19 additions & 0 deletions
19
String/Longest Substring without repeating characters/Solution.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import java.util.*; | ||
|
||
class Solution { | ||
public int lengthOfLongestSubstring(String s) { | ||
int n = s.length(); | ||
Set<Character> set = new HashSet<>(); | ||
int ans = 0, i = 0, j = 0; | ||
while (i < n && j < n) { | ||
// try to extend the range [i, j] | ||
if (!set.contains(s.charAt(j))) { | ||
set.add(s.charAt(j++)); | ||
ans = Math.max(ans, j - i); | ||
} else { | ||
set.remove(s.charAt(i++)); | ||
} | ||
} | ||
return ans; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
#### LeetCode link: | ||
> https://leetcode.com/problems/string-to-integer-atoi/ | ||
### Problem Statement: | ||
|
||
Implement atoi which converts a string to an integer. | ||
|
||
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. | ||
|
||
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. | ||
|
||
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. | ||
|
||
If no valid conversion could be performed, a zero value is returned. | ||
|
||
**Note**: | ||
|
||
- Only the space character ' ' is considered as whitespace character. | ||
|
||
- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2<sup>31</sup>, 2<sup>31</sup> − 1]. If the numerical value is out of the range of representable values, INT_MAX (2<sup>31</sup> − 1) or INT_MIN (−2<sup>31</sup>) is returned. | ||
|
||
**Example 1:** | ||
> Input: 42 | ||
> Ouput: 42 | ||
**Example 2:** | ||
> Input: " -42" | ||
> Output: -42 | ||
> Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42. | ||
**Example 3:** | ||
> Input: "4193 with words" | ||
> Output: 4193 | ||
> Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. | ||
**Example 4:** | ||
> Input: "words and 987" | ||
> Output : 0 | ||
> Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed. | ||
**Example 5:** | ||
> Input : "-91283472332" | ||
> Output: -2147483648 | ||
> Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Therefore INT_MIN (−2<sup>31</sup>) is returned. | ||
### Solution: | ||
|
||
**Steps** | ||
|
||
> The algorithm can be summarised as follows | ||
>> 1. Discard all the whitespaces at the beginning of the string. | ||
>> 2. There could be an optional sign of a numerical value +/-+/−. It should be noted that the integer is positive by default if there is no sign present and there could be at most one sign character. | ||
>> 3. Build the result using the above algorithm until there exists a non-whitespace character that is a number (00 to 99). Simultaneously, check for overflow/underflow conditions at each step. | ||
**Note:** | ||
> If there exists any non-integer character at step 3, we return 0 by default since it is not a valid integer. | ||
> Also, we have to just discard all the characters after the first numerical value. | ||
**Complexity Analysis** | ||
> **Time Complexity:** O(N). Here, N is the length of string str. We perform only one iteration over string str. | ||
> **Space Complexity:** O(1). We use constant extra space for storing sign of the result. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
class Solution { | ||
public int myAtoi(String str) { | ||
int i = 0; | ||
int sign = 1; | ||
int result = 0; | ||
if (str.length() == 0) | ||
return 0; | ||
|
||
// Discard whitespaces in the beginning | ||
while (i < str.length() && str.charAt(i) == ' ') | ||
i++; | ||
|
||
// Check if optional sign if it exists | ||
if (i < str.length() && (str.charAt(i) == '+' || str.charAt(i) == '-')) | ||
sign = (str.charAt(i++) == '-') ? -1 : 1; | ||
|
||
// Build the result and check for overflow/underflow condition | ||
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') { | ||
if (result > Integer.MAX_VALUE / 10 | ||
|| (result == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > Integer.MAX_VALUE % 10)) { | ||
return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE; | ||
} | ||
result = result * 10 + (str.charAt(i++) - '0'); | ||
} | ||
return result * sign; | ||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters