Oracle Leet Code
Oracle Leet Code
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Example 2:
Input: s = "bbbbb"
Output: 1
Example 3:
Input: s = "pwwkew"
Output: 3
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
Solutions:
C++
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
int res = 0;
return res;
unordered_set<char> chars;
char c = s[i];
if(chars.count(c)){
return false;
chars.insert(c);
return true;
};
Java
public class Solution {
int n = s.length();
int res = 0;
if (checkRepetition(s, i, j)) {
return res;
char c = s.charAt(i);
if(chars.contains(c)){
return false;
chars.add(c);
}
return true;
Python
int n = s.length();
int res = 0;
if (checkRepetition(s, i, j)) {
return res;
char c = s.charAt(i);
if(chars.contains(c)){
return false;
chars.add(c);
return true;
}
20. Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
1 <= s.length <= 10 4
Solutions:
Java
class Solution {
// Initialize hash map with mappings. This simply makes the code easier to read.
public Solution() {
this.mappings.put(')', '(');
this.mappings.put('}', '{');
this.mappings.put(']', '[');
char c = s.charAt(i);
python:
class Solution(object):
"""
:type s: str
:rtype: bool
"""
stack = []
# Hash map for keeping track of mappings. This keeps the code very clean.
for char in s:
if char in mapping:
The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -
2.7335 would be truncated to -2.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2 , 2 − 1]. For
31 31
this problem, if the quotient is strictly greater than 2 - 1, then return 2 - 1, and if the quotient is strictly less than -2 , then return -
31 31 31
2 .
31
Example 1:
Output: 3
Example 2:
Output: -2
Constraints:
-231
<= dividend, divisor <= 2
31
- 1
divisor != 0
SOLUTIONS:
C++
return INT_MAX;
int negatives = 2;
if (dividend > 0) {
negatives--;
dividend = -dividend;
if (divisor > 0) {
negatives--;
divisor = -divisor;
int quotient = 0;
dividend -= divisor;
quotient--;
* it to positive. */
if (negatives != 1) {
return -quotient;
}
return quotient;
JAVA
return Integer.MAX_VALUE;
int negatives = 2;
if (dividend > 0) {
negatives--;
dividend = -dividend;
if (divisor > 0) {
negatives--;
divisor = -divisor;
quotient--;
dividend -= divisor;
* it to positive. */
if (negatives != 1) {
quotient = -quotient;
return quotient;
PYTHON
# Constants.
return MAX_INT
# We need to convert both numbers to negatives
negatives = 2
if dividend > 0:
negatives -= 1
dividend = -dividend
if divisor > 0:
negatives -= 1
divisor = -divisor
quotient = 0
quotient -= 1
dividend -= divisor
# it to positive.
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly
once.
Example 1:
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Output: [[""]]
Example 3:
Output: [["a"]]
Constraints:
SOLUTIONS:
JAVA
class Solution {
char[] ca = s.toCharArray();
Arrays.sort(ca);
ans.get(key).add(s);
}
}
PYTHON
class Solution(object):
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
55. Jump Game
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your
maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Example 1:
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible
to reach the last index.
Constraints:
SOLUTIONS:
JAVA
enum Index {
}
public class Solution {
Index[] memo;
if (memo[position] != Index.UNKNOWN) {
if (canJumpFromPosition(nextPosition, nums)) {
memo[position] = Index.GOOD;
return true;
memo[position] = Index.BAD;
return false;
memo[i] = Index.UNKNOWN;
}
memo[memo.length - 1] = Index.GOOD;
}
134. Gas Station
There are n gas stations along a circular route, where the amount of gas at the i station is gas[i].
th
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the i station to its next (i + 1) station. You begin the
th th
Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise
direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique
Example 1:
Output: 3
Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Example 2:
Output: -1
Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
Constraints:
n == gas.length == cost.length
1 <= n <= 10
5
SOLUTIONS:
C++
class Solution {
public:
if (currGain < 0) {
answer = i + 1;
currGain = 0;
}
};
JAVA
class Solution {
if (currGain < 0) {
answer = i + 1;
currGain = 0;
PYTHON3
class Solution:
curr_gain = 0
answer = 0
for i in range(len(gas)):
if curr_gain < 0:
curr_gain = 0
answer = i + 1
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
int get(int key) Return the value of the key if the key exists, otherwise return -1.
void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If
the number of keys exceeds the capacity from this operation, evict the least recently used key.
The functions get and put must each run in O(1) average time complexity.
Example 1:
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
Constraints:
Solutions:
C++
previousEnd->next = node;
node->prev = previousEnd;
node->next = tail;
tail->prev = node;
Java
node.prev = previousEnd;
node.next = tail;
tail.prev = node;
Python3
previous_end = self.tail.prev
previous_end.next = node
node.prev = previous_end
node.next = self.tail
self.tail.prev = node
273. Integer to English Words
Example 1:
Example 2:
Example 3:
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Constraints:
Solutions:
java
class Solution {
switch(num) {
return "";
switch(num) {
return "";
switch(num) {
return "";
if (num == 0)
return "";
return twoLessThan20(num);
else {
if (rest != 0)
else
return ten(tenner);
if (hundred*rest != 0)
res = two(rest);
return res;
}
public String numberToWords(int num) {
if (num == 0)
return "Zero";
if (billion != 0)
if (million != 0) {
if (! result.isEmpty())
if (thousand != 0) {
if (! result.isEmpty())
if (rest != 0) {
if (! result.isEmpty())
result += " ";
result += three(rest);
return result;
Python:
class Solution:
"""
:rtype: str
"""
def one(num):
switcher = {
1: 'One',
2: 'Two',
3: 'Three',
4: 'Four',
5: 'Five',
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine'
}
return switcher.get(num)
def two_less_20(num):
switcher = {
10: 'Ten',
11: 'Eleven',
12: 'Twelve',
13: 'Thirteen',
14: 'Fourteen',
15: 'Fifteen',
16: 'Sixteen',
17: 'Seventeen',
18: 'Eighteen',
19: 'Nineteen'
return switcher.get(num)
def ten(num):
switcher = {
2: 'Twenty',
3: 'Thirty',
4: 'Forty',
5: 'Fifty',
6: 'Sixty',
7: 'Seventy',
8: 'Eighty',
9: 'Ninety'
return switcher.get(num)
def two(num):
if not num:
return ''
return one(num)
return two_less_20(num)
else:
tenner = num // 10
def three(num):
return two(rest)
elif hundred and not rest:
if not num:
return 'Zero'
result = ''
if billion:
if million:
if thousand:
if rest:
result += three(rest)
return result
300. Longest Increasing Subsequence
Given an integer array nums, return the length of the longest strictly increasing subsequence.
Example 1:
Output: 4
Example 2:
Output: 4
Example 3:
Output: 1
Constraints:
Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?
Solutions:
Java
class Solution {
Arrays.fill(dp, 1);
}
}
int longest = 0;
return longest;
Python3
class Solution:
dp = [1] * len(nums)
for j in range(i):
return max(dp)
316. Remove Duplicate Letters
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in
lexicographical order among all possible results.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
Solutions:
Java
// we create a counter and end the iteration once the suffix doesn't have each unique character
// pos will be the index of the smallest character we encounter before the iteration ends
int pos = 0;
// our answer is the leftmost letter plus the recursive call on the remainder of the string
// note that we have to get rid of further occurrences of s[pos] to ensure that there are no
duplicates
Python:
class Solution:
# we create a counter and end the iteration once the suffix doesn't have each unique character
# pos will be the index of the smallest character we encounter before the iteration ends
c = Counter(s)
pos = 0
for i in range(len(s)):
c[s[i]] -=1
if c[s[i]] == 0: break
# our answer is the leftmost letter plus the recursive call on the remainder of the string
# note we have to get rid of further occurrences of s[pos] to ensure that there are no duplicates
The encoding rule is: k[encoded_string], where the encoded_string inside the square
brackets is being repeated exactly k times. Note that k is guaranteed to be a positive
integer.
You may assume that the input string is always valid; there are no extra white spaces,
square brackets are well-formed, etc. Furthermore, you may assume that the original
data does not contain any digits and that digits are only for those repeat numbers, k.
For example, there will not be input like 3a or 2[4].
The test cases are generated so that the length of the output will never exceed 105.
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
Example 3:
Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"
Constraints:
Solutions:
C++
class Solution {
public:
string decodeString(string s) {
stack<char> stack;
if (s[i] == ']') {
string decodedString = "";
decodedString += stack.top();
stack.pop();
stack.pop();
int base = 1;
int k = 0;
stack.pop();
base *= 10;
while (k != 0) {
stack.push(decodedString[j]);
k--;
}
// push the current character to stack
else {
stack.push(s[i]);
string result;
stack.pop();
return result;
};
Java
class Solution {
if (s.charAt(i) == ']') {
decodedString.add(stack.pop());
}
// pop [ from the stack
stack.pop();
int base = 1;
int k = 0;
base *= 10;
while (k != 0) {
stack.push(decodedString.get(j));
k--;
else {
stack.push(s.charAt(i));
}
697. Degree of an Array
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its
elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
Example 2:
Output: 6
Explanation:
Constraints:
Solutions:
Python
class Solution(object):
for i, x in enumerate(nums):
right[x] = i
count[x] = count.get(x, 0) + 1
ans = len(nums)
degree = max(count.values())
for x in count:
if count[x] == degree:
return ans
Java
class Solution {
int x = nums[i];
right.put(x, i);
if (count.get(x) == degree) {
}
return ans;
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left).
Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will
explode. Two asteroids moving in the same direction will never meet.
Example 1:
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Output: []
Example 3:
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Constraints:
Solutions:
C++
class Solution {
public:
stack<int> st;
for (int asteroid : asteroids) {
int flag = 1;
// Hence pop it from the stack, also continue with the next asteroid in the
stack.
st.pop();
continue;
// If both asteroids are the same size, then both asteroids will explode.
// Pop the asteroid from the stack; also, we won't push the current asteroid to
the stack.
st.pop();
flag = 0;
break;
if (flag) {
st.push(asteroid);
// Add the asteroids from the stack to the vector in the reverse order.
remainingAsteroids[i] = st.top();
st.pop();
return remainingAsteroids;
};
Java
class Solution {
// Hence pop it from the stack, also continue with the next asteroid in the
stack.
st.pop();
continue;
// If both asteroids have the same size, then both asteroids will explode.
// Pop the asteroid from the stack; also, we won't push the current asteroid to
the stack.
st.pop();
flag = false;
break;
}
if (flag) {
st.push(asteroid);
// Add the asteroids from the stack to the vector in the reverse order.
remainingAsteroids[i] = st.peek();
st.pop();
return remainingAsteroids;
You are given an array of events where events[i] = [startDay , endDay , value ]. The i event starts at startDay and ends at endDay ,
i i i
th
i i
and if you attend this event, you will receive a value of value . You are also given an integer k which represents the maximum number of
i
You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day
is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.
Return the maximum sum of values that you can receive by attending events.
Example 1:
Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
Output: 7
Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.
Example 2:
Output: 10
Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.
Example 3:
Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3
Output: 9
Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.
Constraints:
Solutions:
Java
class Solution {
int n = events.length;
Arrays.fill(row, -1);
}
return 0;
if (dp[count][curIndex] != -1) {
return dp[count][curIndex];
return dp[count][curIndex];
left = mid + 1;
} else {
right = mid;
return left;
}
}
Python
class Solution:
events.sort()
n = len(events)
if count == 0 or cur_index == n:
return 0
if dp[count][cur_index] != -1:
return dp[count][cur_index]
return dp[count][cur_index]
return dfs(0, k)
Return the minimum possible value of the maximum integer of nums after performing any number of operations.
Example 1:
Input: nums = [3,7,1,6]
Output: 5
Explanation:
The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
Therefore, we return 5.
Example 2:
Output: 10
Explanation:
It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.
Constraints:
n == nums.length
2 <= n <= 10
5
Solutions:
C++
class Solution {
public:
int minimizeArrayValue(vector<int>& nums) {
// Initialize answer and the prefix sum.
long long answer = 0, prefixSum = 0;
return answer;
}
};
Java
class Solution {
public int minimizeArrayValue(int[] nums) {
// Initialize answer and the prefix sum.
long answer = 0, prefixSum = 0;
return (int)answer;
}
}
Python3
class Solution:
def minimizeArrayValue(self, nums: List[int]) -> int:
# Initialize answer and the prefix sum.
answer = 0
prefix_sum = 0
return answer
2472. Maximum Number of Non-overlapping Palindrome Substrings
Select a set of non-overlapping substrings from the string s that satisfy the following conditions:
Example 1:
Input: s = "abaccdbbd", k = 3
Output: 2
Explanation: We can select the substrings underlined in s = "abaccdbbd". Both "aba" and "dbbd" are palindromes and have
a length of at least k = 3.
It can be shown that we cannot find a selection with more than two valid substrings.
Example 2:
Input: s = "adbcda", k = 2
Output: 0
Constraints:
Solutions:
2539. Count the Number of Good Subsequences
A subsequence of a string is good if it is not empty and the frequency of each one of its characters is the same.
Given a string s, return the number of good subsequences of s. Since the answer may be too large, return it modulo 10 + 7.
9
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the
remaining characters.
Example 1:
Input: s = "aabb"
Output: 11
Explanation: The total number of subsequences is 2 . There are five subsequences which are not good: "aabb", "aabb",
4
"aabb", "aabb", and the empty subsequence. Hence, the number of good subsequences is 2 -5 = 11. 4
Example 2:
Input: s = "leet"
Output: 12
Explanation: There are four subsequences which are not good: "leet", "leet", "leet", and the empty subsequence. Hence,
the number of good subsequences is 2 -4 = 12.
4
Example 3:
Input: s = "abcd"
Output: 15
Explanation: All of the non-empty subsequences are good subsequences. Hence, the number of good subsequences is 2 -1 = 4
15.
Constraints:
Solutions: