Given a string s, find the length of the longest substring without repeating characters.
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.
Double for loop is brute force.
Time = O(N) Space = O(26), constant since we have 26 characters in the alphabet
class Solution:
Falling dominos
Given a string with the initial condition of dominoes, where:
. represents that the domino is standing still
L represents that the domino is falling to the left side
R represents that the domino is falling to the right side
Figure out the final position of the dominoes. If there are dominoes that get pushed on both ends, the force cancels out and that domino remains upright.
dominos = "..R..LL..R." answer = ..RRLLL..RR
you can do this in a very methodical way in which you get 2 lists of left and rights, then once you get the lists you can iterate through them to create a final list by going right, then left
time: O(n), 3n because we loop through it forward, backwards, and again to make the final string
space: O(n), 2n because we have the force list and the response list. response list helps us reduce the string appending to linear time vs quadradic (confirm with documentation)
class Solution:
list strategies for strings
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
Example 2:
Input: s = “loveleetcode”
Output: 2
class Solution:
time: O(n), double loop,
space: O(26), constant time bc we use a hashmap with alphabet keys
validate parenthesis
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
time: linear
space: linear
class Solution:
generate parenthesis
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: [”((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
Example 2:
Input: n = 1
Output: [”()”]
brute force is to get all possible permutations, check if they are valid, then return the valid ones. Returning the cartesian products (permutations) of N items with a total length of S is N^S. time and space are 2^(2N) here
class Solution:
time: O(4^n / n^0.5) Catalan number, which is 4^n / (n^1.5), and for each iteration, we have to append something of N length, so it increases it to 4^n / n^0.5. Realistically, if you gave 2^2n * n it would be acceptable.
space: same as above, we must store each answer which is the catalan number, and each catalan number is N length so multiply them you get O(4^n / n^0.5)
Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
brute force/intuition is backtracking
time: O((4^n)*N), worst case of 7/9s we have 4 choices for each digit, and at each combination we need to concatenate the current to the output which takes N time
space: O(n) not including the output or the hashmap since that is constant, we care about the recursion tree height which is only ever N
class Solution:
Score of parentheses
Given a balanced parentheses string s, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
”()” has score 1.
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: s = “()”
Output: 1
Example 2:
Input: s = “(())”
Output: 2
Example 3:
Input: s = “()()”
Output: 2
Example 4:
Input: s = “(()(()))”
Output: 6
brute force is a crazy divide and conquer, N^2 time and N space for the recursion stack
class Solution:
time: O(n)
space: O(n) bc of the stack, could get n sized
time: O(n)
space: constant
Valid palindrome
(string includes non-alpha-numeric characters, we need to ignore those)
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.
brute is to check if the reversed string is the same as original after we lowercase everything and remove the non-alphanumeric ones, with linear time and space
time: O(N) where N is s
space: cosntant
class Solution:
palindrome number
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
brute force is convert to string, see if s == s[::-1]
time: Log base 10 (N), you can also say it is linear with respect to the number of 10’s that can be divided into it, but log10(N) probably sound smarter
space: constant
class Solution:
Implement strStr():
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
Example 1:
Input: haystack = “hello”, needle = “ll”
Output: 2
Example 2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
brute force is to do O(n * (m - n)) where m and n are haystack/needle. This makes sure that you are never going out of index of the haystack. hay = 5, needle = 3, 5 - 3 = 2, but that means we only get 0 and 1 indexes, if it is aabcd and bcd, then we miss it, so we add 1 (standard index subtraction to make sure we don’t lose an index)
https://www.youtube.com/watch?v=GTJr8OvyEVQ
time: O(n * (m - n))
space: constant
https: //www.youtube.com/watch?v=GTJr8OvyEVQ
1. KMP, memorize it!
2. make sure to check edge cases, bc KMP does not check if they are none and such
time: O(haystack + needle). KMP requires us to make the longest proper suffix (LPS) array which is needle, then the search takes haystack time
space: O(needle) for the LPS array
class Solution:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
Example 1:
Input: strs = [“flower”,”flow”,”flight”]
Output: “fl”
time: O(S ) where S is the total length of characters, you could also say O(S * L) where S is the length of the string list and L is the length of the longest string,
space: constant
class Solution:
time: O(S ) where S is the total length of characters, you could also say O(S * L) where S is the length of the string list and L is the length of the longest string,
space: constant
reverse a string
time: O(N), N/2 actually
space: constant, recursive is N/2
class Solution:
reverse words in string
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = “the sky is blue”
Output: “blue is sky the”
Example 2:
Input: s = “ hello world “
Output: “world hello”
Explanation: Your reversed string should not contain leading or trailing spaces.
brute is to use factory methods, linear time and space
from collections import deque
class Solution:
----def factory(self, s):
--------return " ".join(reversed(s.split()))
--------'''
--------s ="b".join("ac") = abc
--------s ="b".join("a") = a
--------print(s)
--------'''time: O(N), where N is the size of s
space: O(N)
I got this my first try! worked and everything, but not optimized bc we add spaces after the fact instead of during
reverse words in a string 3
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
time/space are linear. the iteration takes N time, the reverse will add N time as well, then appending to the response list is N time.
from collections import deque class Solution: ----def factory_methods(self, s: str) -> str: --------return " ".join([w[::-1] for w in s.split()])
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
time: O(n), we go through both lists once bc they need to be the same size
space: O(26), the hashmap can only have 26 characters so it is constant
from collections import defaultdict class Solution: ----def isAnagram(self, s: str, t: str) -> bool: --------if len(s) != len(t): ------------return False -------- --------map = defaultdict(int) --------# for x, y in zip(s, t): ------------# map[x] += 1 ------------# map[y] -= 1 ------------ --------for i in range(len(s)): ------------map[s[i]] += 1 ------------map[t[i]] -= 1 -------- --------for key, value in map.items(): ------------if value != 0: ----------------return False ------------ --------return True
can place flowers
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0’s and 1’s, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
time: O(n)
space: constant, if we cannot modify the input array then it would be linar
class Solution:
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.
For example, “0.1.2.201” and “192.168.1.1” are valid IP addresses, but “0.011.255.245”, “192.168.1.312” and “192.168@1.1” are invalid IP addresses.
Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
Example 1:
Input: s = “25525511135”
Output: [“255.255.11.135”,”255.255.111.35”]
Example 2:
Input: s = “0000”
Output: [“0.0.0.0”]
time: O(3^n) where n is the valid number of octets. in this example, n = 4 so it is constant at 81
space: O(n) where n is the number of valid octets due to backtracking, in this case 4. for response array, it is O(1) bc we can calculate how many ip’s at each string length.
class Solution: