JCSU Unit 1 Problem Set 2 (Click for link to problem statements)
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?
2n
elements where the first half contains xi
elements and the second half contains yi
elements, such that the result alternates as [y1, x1, y2, x2, ..., yn, xn]
.HAPPY CASE
Input:
pairs = [1, 2, 3, 4, 5, 6]
Output:
[2, 1, 4, 3, 6, 5]
Explanation:
The pairs are reversed as [2, 1], [4, 3], [6, 5]
.
EDGE CASE Input: pairs = [] Output: [] Explanation: An empty list results in an empty 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 array reordering problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea:
Split the array into two halves. Iterate through both halves simultaneously, appending elements from the second half followed by the first half into a new list.
n
of the list, which is len(pairs) // 2
.result
.i
from 0 to n - 1
:
i-th
element from the second half of pairs
to result
.i-th
element from the first half of pairs
to result
.result
.Implement the code to solve the algorithm.
def reverse_pairs(pairs):
n = len(pairs) // 2 # Determine the number of pairs (half the list length)
result = []
for i in range(n):
result.append(pairs[n + i]) # Add the 'yi' element from the second half
result.append(pairs[i]) # Add the corresponding 'xi' element from the first half
return result # Return the reordered list with reversed pairs
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
Example 2:
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume n is half the size of the input list.