Leetcode

Ace your homework & exams now with Quizwiz!

Roman integer conversion to integers

"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000,

O(1) + O(1) =

=O(1)

Missing number problem: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2

Answer:

Given an array of size n, find the majority element. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3

Approach: Sorting class Solution: def majorityElement(self, nums): nums.sort() return nums[len(nums)//2] Complexity Analysis Time complexity : O(nlgn) *Sorting the array costs O(nlgn) time in Python and Java, so it dominates the overall runtime. *Space complexity : O(1) or (O(n) We sorted nums in place here - if that is not allowed, then we must spend linear additional space on a copy of nums and sort the copy instead.

Landau's symbol after who?

Comes from the name of the German number theoretician Edmund Landau who invented the notation.

Constant time complexity

Describes algorithms that take the same amount of time to compute regardless of the input size. For instance, if a function takes the identical time to process ten elements as well as 1 million items, then we say that it has a_____________ growth rate or O(1). Examples of constant runtime algorithms: Find if a number is even or odd. Check if an item on an array is null.

Divide and conquer steps

Divide: Given a problem, identify a number of significantly smaller subproblems. Conquer: Solve each subproblem recursively (do this until the subproblem is a base-case). Combine: these solutions into a solution for the main problem.

Product of Array Except Self (Approach 1: Left and Right product lists) intuition

For every given index, i, we will make use of the product of all the numbers to the left of it and multiply it by the product of all the numbers to the right. This will give us the product of all the numbers except the one at the given index i.

Difference between increasing and non-decreasing

Increasing - 1 2 3 4 Nondecreasing - 1 1 2 3 The difference being that in an increasing sequence, for x(n) and x(n+1), x(n+1) > x(n) whereas in a non-decreasing sequence, x(n+1) >= x(n) non-decreasing means every next element isn't less then previous, and increasing means every next element is greater then previous

A "single pass"

Means that each element in a collection of elements (be it: a list, an array, a set, a vector, a map, a tree, a graph, a string, etc.) is visited ("iterated over") once and only once - it doesn't matter if the procedure is recursive or iterative.

The join() method

Method that takes all items in an iterable and joins them into one string. A string must be specified as the separator. Example: myTuple = ("John", "Peter", "Vicky") x = "#".____(myTuple) print(x) Output: John#Peter#Vicky Think of glue!

What is DXCI as an integer?

Now, notice that this time the symbols are not ordered from most significant to least—the X and C are out of numeric order. Because of this, we subtract the value of X (10) from the value of C (100) to get 90. So, going from left to right, we have D + (C - X) + I = 500 + 90 + 1 = 591.

Constant time complexity notation (big O)

O(1)

Answer: O(log N) We have to find the smallest x such that `N / 2^x < 1 OR 2^x > N` x = log(N)

O(N) O(Sqrt(N)) O(N / 2) O(log N) O(log(log N))

Linear time complexity notation (big O)

O(n)

Quadratic time complexity notation (big O)

O(n^2)

Why convert to set in Missing Number problem?

Set gets rid of all duplicates and has O(1) https://www.reddit.com/r/learnpython/comments/hxa13u/reasoning_behind_converting_to_a_set/

Roman to Integer problem: (Left-to-Right Pass approach) Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.

Solution (Python): The simplest algorithm is to use a pointer to scan through the string, at each step deciding whether to add the current symbol and go forward 1 place, or add the difference of the next 2 symbols and go forward 2 places.

Majority element problem (using Boyer-Moore): Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3

Solution(Java):

Boyer-Moore majority vote algorithm

This algorithm decides which element of a sequence is in the majority, provided there is such an element. It uses linear time and constant space.

IVX LCD M

Trick to remember roman numberal sequence

Answer: Complexity Analysis Time complexity : O(N) to swap N/2 element. Space complexity : O(1), it's a constant space solution.

What's the complexity analysis of this code?

Answer: Time complexity: O(m*n) Space complexity: O(m) Which is fine for smaller inputs, but far too slow for larger ones.

What's the time and space complexity? Why is this solution inefficient (Ransome note problem)?

Answer: Complexity Analysis Time complexity : O(N) since we go through the string of length N two times. Space complexity : O(1) because English alphabet contains 26 letters.

What's the time/space complexity?

seq_string = 'Python' print(list(reversed(seq_string))) what's the output?

['n', 'o', 'h', 't', 'y', 'P'] Reverse # for string

Array rotation using Extra Array code line (where rotation happens)

a[(i + k) % n] = nums[i] a: the extra array nums: original input array Remember aikEn

gcd

greatest common divisor

Boyer-Moore majority vote algorithm complexity (time and space)

the algorithm takes time O(n) (linear time) on an input sequence of n items, because it performs only a constant number of operations per input item. constant space O(1)

Kids With the Greatest Number of Candies intuition Given the array candies and the integer extraCandies, where candies[i]represents the number of candies that the ith kid has. For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies. Example: Input: candies = [2,3,5,1,3], extraCandies = 3 Output: [true,true,true,false,true]

use array to append answer for all kids use range to iterate and compare to max of the array

Shortest Word Distance Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. Example:Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. Input: word1 = "coding", word2 = "practice" Output: 3 Input: word1 = "makes", word2 = "coding" Output: 1 Note:You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

Answer (Python):

X (Roman numeral)

10 as an integer

C (Roman Numeral)

100 as an integer

M (Roman Numeral)

1000 as an integer

In Ransom Note Problem (Two hashmaps approach), pay attention to

Pay attension to the constraint, and that empty spaces are not supported, so strings needs to be lowercase letters only in test case (unless otherwise)

L (roman numeral)

50 as an integer

D (Roman Numeral)

500 as an integers

IVXLCDM

7 Roman numerals sequence

class collections.Counter c = Counter() # a new, empty counter c = Counter('gallahad') # a new counter from an iterable

A ________ is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.

Boyer-Moore majority vote algorithm caveat?

A version of the algorithm that makes a second pass through the data can be used to verify that the element found in the first pass really is a majority. (sometimes needed) does not work properly if there is no majority

Time complexity

A way of showing how the runtime of a function increases as the size of the input increases

Big O notation (with a capital letter O, not a zero)

Also called Landau's symbol, is a symbolism used in complexity theory, computer science, and mathematics to describe the asymptotic behavior of functions. Basically, it tells you how fast a function grows or declines.

Brute-force search or exhaustive search

Also known as generate and test, is a very general problem-solving technique and algorithmic paradigm that consists of systematically enumerating all possible candidates for the solution and checking whether each candidate satisfies the problem's statement.

Linear time complexity

An algorithm is said to take __________time, or O(n) time, if its time complexity is O(n). Informally, this means that the running time increases at most linearly with the size of the input.

Reverse String problem (using Two Pointers) Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters. Example 1: Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"]

Answer (Python): Complexity Analysis Time complexity : O(N) to swap N/2 element. Space complexity : O(1), it's a constant space solution. In this approach, two pointers are used to process two array elements at the same time. Usual implementation is to set one pointer in the beginning and one at the end and then to move them until they both meet.

Ransom Note Problem (Two hashmaps approach): Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Example: Input: ransomNote = "aa", magazine = "aab" Output: true Constraints: You may assume that both strings contain only lowercase letters.

Answer (Two hashmaps approach): Time complexity: O(m) Space Complexity : O(1) because only 26 letters exist

Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has. For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies. Example : Input: candies = [2,3,5,1,3], extraCandies = 3 Output: [true,true,true,false,true]

Answer:

Move zeroes: Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array.

Answer:

Best Time to Buy and Sell Stock II Say you have an array prices for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [7,1,5,3,6,4] Output: 7

Answer: (In Java)

Ransome Note Problem (initial inefficient solution) pseudocode:

Answer: (We do the character deletion so that the next loop only checks the remaining characters)

Boyer-Moore majority vote algorithm intuition

Answer: As we sweep we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate is unknown and the counter is 0. When we move the pointer forward over an element e: *If the counter is 0, we set the current candidate to e and we set the counter to 1. *If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate. When we are done, the current candidate is the majority element, if there is a majority. Link: http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html

Ransom Note Problem (Two hashmaps approach) intuition:

Answer: We can make two HashMaps; one for the magazine, and the other for the ransom note. Then, to actually check whether or not the ransom note can be made using the magazine, we should loop over each character of the ransom note, checking how many of it we need, and checking that at least that many exist in the magazine, by looking it up in the magazine HashMap. Example in image: ransom note "leetcode is cool magazine "close call as fools take sides"

If n is the size of input(positive), which function is the most efficient? In other words, which loop completes the fastest. A) for(i = 0; i < n; i++) B) for(i = 0; i < n; i += 2) C) for(i = 1; i < n; i *= 2) D) for(i = n; i > -1; i /= 2)

Answer: C The time complexity of the first for loop is O(n). The time complexity of the second for loop is O(n/2), equivalent to O(n) in asymptotic analysis. The time complexity of the third for loop is O(logn). The fourth for loop doesn't terminate.

BCR

Best conceivable runtime

Solve problem in image, answer in text:

Explanation *********************** Correct answer: 5 First, because of the placement of the return statement, the outer loop will only run once before the function returns a value. So, the lines of the inner loop are the only ones which can be executed multiple times. Line 5 controls whether the body of the inner loop runs, so it will be executed once for each iteration through the loop. However, it will also be run a final time in order to break the loop, so it ends up being the most executed line.

The majority element

Given an array of size n, it's the element that appears more than ⌊ n/2 ⌋ times.

Divide and conquer

Has a recursive step, where subproblems are solved, and a base case, which is the point where the problem can't be broken down any further.

Lemma

In mathematics, informal logic and argument mapping, a ______ is a generally minor, proven proposition which is used as a stepping stone to a larger result.

Space complexity

Is a measure of how efficient your code is in terms of memory used.

Describe binary search

Is a popular example that uses decrease and conquer. __________ looks through a sorted list to see if a desired element is in the list. It does this efficiently by halving the search space during each iteration of the program. Basically,_________ finds the middle of the list, asks "is the element I'm looking for larger or smaller than this?" and then cuts the list in half and searches only in the left list if the element is smaller, and the right list if the element is bigger. It repeats this process until it finds the element it is looking for (or reports back that the element isn't in the list at all).

Divide and conquer

Is a powerful algorithm design technique used to solve many important problems such as mergesort, quicksort, calculating Fibonacci numbers, and performing matrix multiplication.

Divide and conquer

Is a way to break complex problems into smaller problems that are easier to solve, and then combine the answers to solve the original problem.

quadratic time

O(N²) — ________ Time Complexity represents an algorithm whose performance is directly proportional to the squared size of the input data set (think of Linear, but squared). Within our programs, this time complexity will occur whenever we nest over multiple iterations within the data sets.

Longest Substring Without Repeating Characters (use range) Given a string, find the length of the longest substring without repeating characters. Example: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.

Solution (Python): https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1731/A-Python-solution-85ms-O(n)

Ransome Note Problem (initial inefficient solution): Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Example: Input: ransomNote = "aa", magazine = "aab" Output: true Constraints: You may assume that both strings contain only lowercase letters.

Solution (inefficient for larger inputs) Time complexity: O(m*n) Space complexity: O(m)

Reverse Words in a String III (1 Python line) Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space and there will not be any extra space in the string.

Solution:

Two Sum problem (use dictionaries) Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9 Because nums[0] + nums[1] = 2 + 7 = 9 return [0, 1].

Solution:

Product of Array Except Self (Approach 1: Left and Right product lists) Given an array nums of n integers where n > 1, return an array outputsuch that output[i] is equal to the product of all the elements of numsexcept nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. Note: Please solve it without division and in O(n). Follow up:Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

Solution: Attn to the R portion and how indexing works. Complexity analysis Time complexity : O(N) where N represents the number of elements in the input array. We use one iteration to construct the array L, one to construct the array R and one last to construct the answeranswer array using L and R. Space complexity : O(N) used up by the two intermediate arrays that we constructed to keep track of product of elements to the left and right.

First Unique Character in a String (Method: Hashmap) Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode" return 2. Note: You may assume the string contains only lowercase English letters.

Solution: Time complexity : O(N) since we go through the string of length N two times. Space complexity : O(1)because English alphabet contains 26 letters.

Given an array, rotate the array to the right by k steps, where k is non-negative. Example: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Approach: Using Extra Array

Solution: Time complexity: O(n). One pass is used to put the numbers in the new array. And another pass to copy the new array to the original one. Space complexity: O(n). Another array of the same size is used.

Roman to Integer problem strategy Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Example: Input: "III" Output: 3

Split to if... else for substractive and non-substractive cases, use set to list values of converted romans

Brute Force Algorithms

Straightforward methods of solving a problem that rely on sheer computing power and trying every possibility rather than advanced techniques to improve efficiency.

Python Counter

Takes in input a list, tuple, dictionary, string, which are all iterable objects, and it will give you output that will have the count of each element. list1 = ['x','y','z','x','x','x','y', 'z'] Counter({'x': 4, 'y': 2, 'z': 2})

The continue statement (Python)

The _____ statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but ________ on with the next iteration.

Break vs Continue (python)

The _____ statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the ______ statement is inside a nested loop (loop inside another loop), the _______ statement will terminate the innermost loop. The _____ statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but ________ on with the next iteration.

reversed()

The ________ function returns the reversed iterator of the given sequence.

Greedy algorithm

The idea of ___________ is to pick the locally optimal move at each step, that will lead to the globally optimal solution.

Why big O?

The letter O is used because the rate of growth of a function is also called its order.

What is CMXCIV as an integer?

The symbols barely look sorted at all here—from left-to-right we have 100, 1000, 10, 100, 1, 5. We need to look for each occurrence of a smaller symbols preceding a bigger symbol. The first, third, and fifth symbols are all smaller than their next symbol. Therefore they are all going to be subtracted from their next. The first two symbols are CM. This is M - C = 1000 - 100 = 900 The second two symbols are XC. This is C - X = 100 - 10 = 90. The final two symbols are IV. This is V - I = 5 - 1 = 4. Like we did above, we add these together. (M - C) + (C - X) + (V - I) = 900 + 90 + 4 = 994.

Decrease and Conquer

There is a variation of divide and conquer where the problem is reduced to one subproblem. Binary search is a popular example that uses ___________. Binary search looks through a sorted list to see if a desired element is in the list. It does this efficiently by halving the search space during each iteration of the program. Basically, binary search finds the middle of the list, asks "is the element I'm looking for larger or smaller than this?"

Move Zeroes Strategy Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.

Use j on top of i to keep track of nonzero elements, then fill the gap nums.length - j with zeroes

How to prove that your greedy algorithm provides globally optimal solution?

Usually you could use the proof by contradiction. Ressources: https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/13/Small13.pdf https://leetcode.com/problems/two-city-scheduling/solution/

Answer: Rotates elements of an array. Example: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Time complexity: O(n). One pass is used to put the numbers in the new array. And another pass to copy the new array to the original one. Space complexity: O(n). Another array of the same size is used.

What does it do? Time and space complexity?

Contiguous subarray

With elements all adjacent in space. A subarray is defined by any subset of the indices of the original array; a _______________ is defined by an interval of the indices: a first and last element and everything between them.

Longest Palindromic Substring possible Strategy Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer.

You can parse with i from beginning and j from end. O(n^2), not the most efficient

Possible strategy for Reverse String: Problem: Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You can use Two Pointers technique, though there might be better, briefer.

Possible strategy for Valid Palindrome II Problem: Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example: Input: "aba" Output: True Note: The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

You can use standard two pointer approach. https://leetcode.com/problems/valid-palindrome-ii/

seq_tuple = ('P', 'y', 't', 'h', 'o', 'n') print(list(reversed(seq_tuple))) what's the output?

['n', 'o', 'h', 't', 'y', 'P'] Reverse # for tuple

seq_range = range(5, 9) print(list(reversed(seq_range))) What's the output?

[8, 7, 6, 5] Reverse # for range

sets in python ( set( ) )

_______ are unordered. _______ elements are unique. Duplicate elements are not allowed.

Quadratic Time Complexity

_________ represents an algorithm whose performance is directly proportional to the squared size of the input data set (think of Linear, but squared).

Auxiliary Space vs Space Complexity (ordered answer)

________is the extra space or temporary space used by an algorithm. __________of an algorithm is total space taken by the algorithm with respect to the input size.______________ includes both Auxiliary space and space used by input.

Rotate Array strategy Given an array, rotate the array to the right by ksteps, where k is non-negative. Follow up: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space? Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]

create empty array a of length of nums to be rotated, fill with values after rotation with aikn, nums recieves a

Roman to integer conversion logic

each symbol adds its own value, except for when a smaller valued symbol is before a larger valued symbol.

Big O cheat sheet

https://www.bigocheatsheet.com


Related study sets

Netacad Chapter 6: Network Layer

View Set

Medicare and Medicaid General Compliance Training

View Set

AP U.S. Government Final Exam "Review" with Answers

View Set

Musical Theater Final Listening Section

View Set

Chapter 12: Spinal Cord and Spinal Nerves

View Set

NUR250 Final Group 3 - ARDS - NCLEX questions

View Set