Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Be sure that you clarify the input and output parameters of the problem:
Run through a set of example cases:
HAPPY CASE
Input: "REVERSE"
Output: "ESREVER"
Input: "42 Wallaby Way, Sydney"
Output: "yendyS ,yaW yballaW 24"
EDGE CASE
Input: "
Output: "
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Strings, common solution patterns include:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Start traversing inwards, from both ends of the input string, and we can expect to swap the characters, in the same order.
1. We first convert the string into an array, because a string is immutable.
2. Then we can take two pointer variables, start and end and point them with the two ends of the array.
3. As we move the start pointer right and end pointer left, we swap the characters.
4. After loop finishes, the string is said to be reversed, hence convert the array into a string and return.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
Approach #1: Two Pointer
class Solution:
def reverseString(self, s: List[str]) -> None:
# Take two pointer variables, start and end and point them with the two ends of the array.
l, r = 0, len(s) - 1
# As we move the start pointer right and end pointer left, we swap the characters.
while l < r:
s[l], s[r] = s[r], s[l]
l, r = l + 1, r - 1
# After loop finishes, the string is said to be reversed, hence convert the array into a string and return.
return s
Approach #1: Iterative
class Solution:
def reverseString(self, s: List[str]) -> None:
output_str = "
for i in range(len(input_str) - 1, -1, -1):
output_str += input_str[i]
return output_str
⚠️ Common Mistakes
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Time Complexity: O(n), traversing is done on every character, until the pointers meet in the middle. Time complexity will be O(n) (where n is the length of the given string).
Space Complexity: O(n), we need memory to hold new string or new array, because python strings are immutable.