Interview Preparation
This is a collection of notes on Interview Preparation. This is a work in progress and will be updated regularly.
Two Pointer Pattern
1. Two Sum
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 <= 104
-
-109 <= nums[i] <= 109
-
-109 <= target <= 109
-
Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
Intuition
The problem is to find two numbers in the array that add up to a given target. A straightforward way would be to use two loops and check every combination of two numbers. However, this would be inefficient.
Sorting the array increases time complexity.
A more efficient way would be to use a hashmap (or in JavaScript, a Map) to store the numbers we've seen so far and their indices. As we iterate through the array, for each number, we can check if the difference between the target and that number exists in the map. If it does, we've found our two numbers.
Approach
Using HashMap and Javascript Object
- Initialize an empty Map.
- Iterate through the array.
- For each number, calculate the difference between the target and that number.
- Check if this difference exists in the Map.
- If it does, return the index of the difference from the Map and the current index.
- If not, add the current number and its index to the Map.
Complexity
- Time complexity:
The time complexity is (O(n)) because we iterate through the array once, and operations with the Map (both get and set) are on average (O(1)).
- Space complexity:
The space complexity is (O(n)) because in the worst case, we might store all numbers in the Map.
Code
HashMap
- Map is more memory-intensive because of its advanced functionality and robust key handling.
- The implementation uses a single pass through the array, storing each number's index in a Map.
- Time complexity: O(n) - We traverse the list containing n elements only once.
- Space complexity: O(n) - The extra space required depends on the number of items stored in the hash map, which stores at most n elements.
Object
- Plain objects use slightly less space due to lower overhead.
- The implementation uses a single pass through the array, storing each number's index in an object.
- Time complexity: O(n) - We traverse the list containing n elements only once.
- Space complexity: O(n) - The extra space required depends on the number of items stored in the object, which stores at most n elements.
Javascript Questions
Question 1
Given an integer array nums, return the length of the longest increasing subsequence.
Example:
Subsequence: A subsequence is a sequence derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Increasing Subsequence: A subsequence where each element is greater than the previous one.
Non-Contiguous: The elements of the subsequence do not have to be contiguous in the original array.
Solution
Attempt 1
This was done without understanding the problem statement properly.
-
function finds the longest consecutive increasing subsequence, not the longest increasing subsequence in general. It only compares adjacent elements.
-
solution has a time complexity of O(n) and space complexity of O(n)
-
It will miss non-consecutive increasing subsequences.
Attempt 2
With the help of chatgpt
This JavaScript implementation follows the same logic as the Python version:
-
We first check if the input array is empty. If so, we return 0.
-
We create a
dp
array of the same length as the input array, initialized with all 1s. -
We use nested loops to compare each element with all previous elements.
-
If we find a smaller previous element, we update the current dp value if necessary.
-
Finally, we return the maximum value in the dp array, which represents the length of the longest increasing subsequence.
The time and space complexities remain the same: O(n^2) time and O(n) space, where n is the length of the input array.
Question 2
Define a FruitStand class that allows you to add different types of fruits with their quantities and prices, update them, and calculate the total value of all the fruits in the stand.
Implement the following methods:
addFruit(name, quantity, price)
updateQuantity(name, quantity)
totalValue()
Example usage:
Solution
Question 3
Write a function that takes an array of integers representing the number of flowers planted in a line, and an integer k representing the number of additional flowers you want to plant. Return whether it's possible to plant all k flowers without planting any two flowers adjacent to each other.
Example:
Solution
Question 4
Write a function that takes a list of names and returns the names sorted by the number of vowels in each name in descending order. If two names have the same number of vowels, sort them alphabetically.
Example:
Solution
Question 5
Write a function that takes an array of integers and a target sum, and returns all unique quadruplets [a, b, c, d] in the array such that a + b + c + d = target. If it's impossible, return an empty array.
Example:
Solution
Attempt 1
Pros:
- Straightforward: The logic is simple and easy to understand.
Cons:
-
Time Complexity: The time complexity of this solution is π(π^4), where π is the length of the input array. This is inefficient for larger arrays.
-
Handling Duplicates: This solution does not handle duplicates, so it may return the same quadruplet multiple times if the input array contains duplicate elements.
-
Space Complexity: The space complexity is π(1) for the algorithm itself, but the result array can grow significantly if there are many matching quadruplets.
Attemp 2
Question 6
Write a function that takes an array of integers and returns a new array containing only the even numbers, and sorted.
Example:
Solution
Attempt 1
The solution is concise and leverages JavaScript's higher-order functions filter and sort. However, there is a minor issue with the sort method. By default, the sort method sorts elements as strings, which can lead to incorrect orderings for numerical arrays.
Attempt 2
Complexity:
-
Time Complexity:
Filtering: π(π), where π is the length of the input array. Sorting: π(πlogπ), where π is the number of even numbers. Overall: π(π+πlogβ‘π).
-
Space Complexity: π(π), where π is the number of even numbers, as a new array is created to store the even numbers
Question 7
Write a program that implements the DelayedTaskExecutor interface defined below. Think about how it would work if you ran the exec function multiple times in a row, before the task is run!
Interfaces:
Question 8
Write a function that converts between metric and imperial units. Break up the units into millimeters, centimeters, and meters for metric, and into inches and feet for imperial, up to 2 decimal places.
Example:
Solution
Question 9
The Spanish language uses inverted punctuation marks (ΒΏ and Β‘) in interrogative and exclamatory sentences. Write a function that takes in a string str, and adds ΒΏ and Β‘ if they're needed. You can ignore exclamations in the middle of a sentence for this problem.
Example:
Solution
My version
ChatGPT version
Regular Expression: /([?!])/
Breakdown:
-
/ and /: These are the delimiters for the regular expression in JavaScript.
-
[ and ]: This denotes a character class. A character class matches any one of the characters inside the square brackets.
-
?!
: Inside the character class, this matches either a ? or a !. This means any occurrence of ? or ! will be a match. -
(): Parentheses denote a capturing group. This means whatever matches inside the parentheses will be captured and included in the result of the split.
Question 10
Write a function that takes in a list (of length >= 3) of numbers, and returns the maximum product that can be obtained by multiplying any three integers from the list.
Example:
Solution
Attempt 1
Attempt 2
Question 11
Create a function that should take one argument n, which is a positive integer. The function should return the sum of all squared positive integers between 1 and n, inclusive.
Example:
Solution
Attempt 1
Attempt 2
Question 12
Write a "word wrapping" function that takes in a string and the maximum width of a line of text, and return the text "wrapped" to that line length. Include dashes for broken words (which is included in the length of that line), and don't let a line start with a non-alphanumeric character.
Example:
Solution
Attempt 1
Problems:
- It always adds a hyphen before the newline character, even if the break happens at a space or a punctuation mark, which is not ideal.
- It doesn't handle breaking words correctly to avoid lines starting with non-alphanumeric characters.
- It hardcodes the line length to 10 instead of using the length parameter.
Question 13
Imagine the users on your app are all typing slightly incorrectly, in that they shifted their hands one key to the right. Write a function that translates what they mean to say. The examples below assume an ANSI keyboard layout, you can choose how you want to do that!
Example:
Solution
Handling Edge Cases:
- The current implementation works well for most cases but might fail for characters at the very start of the keyboard string (e.g., 1 or q), as keyboard.indexOf(char) - 1 would access an out-of-bounds index.
- To avoid this, you could add a condition to check if keyboard.indexOf(char) - 1 is less than 0 and handle it appropriately.
Uppercase Letters:
- The function currently doesnβt handle uppercase letters. To support them, you could either extend the keyboard string with uppercase characters or convert the input string to lowercase before processing.
Question 14
Given a direction and a number, write a function that outputs an arrow of asterisks with the height of that number! See the pattern below.
Example:
Solution
Question 15
Given an array of logs and variable assignments, return a list of all unused variables.
Examples:
Solution
Attempt 1
Improvements
- Use of Destructuring: Utilize destructuring to make the code cleaner when splitting the string by =.
- Simplified Conditionals: Simplify the logic for updating the stack by directly assigning values and avoiding unnecessary checks.
- Avoid Repeated Lookups: Remove the need for repeatedly checking the existence of a variable in the stack.
- Consistent Variable Naming: Use meaningful and consistent variable names to make the code easier to follow.
- Remove Redundant Code: Simplify the logic to remove unnecessary checks or operations.