Skip to content

Shuffle

Raymond Chen edited this page Aug 1, 2024 · 2 revisions

TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: Lists, Iteration

U-nderstand

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?
  • The function shuffle() should take a list of 2n elements in the format [x1, x2, ..., xn, y1, y2, ..., yn] and return a new list in the format [x1, y1, x2, y2, ..., xn, yn].
HAPPY CASE
Input: ['Joker', 'Queen', 2, 3, 'Ace', 7]
Expected Output: ['Joker', 3, 'Queen', 'Ace', 2, 7]

Input: [9, 2, 3, 'Joker', 'Joker', 3, 2, 9]
Expected Output: [9, 'Joker', 2, 3, 3, 2, 'Joker', 9]

EDGE CASE
Input: [10, 10, 2, 2]
Expected Output: [10, 2, 10, 2]
    
Input: [] (empty list)
Expected Output: []

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Calculate the midpoint of the list, then iterate through the first half and append elements from both halves to a new list in the specified order.

1. Define the function `shuffle(cards)`.
2. Calculate `n` as half the length of the list `cards`.
3. Initialize an empty list `shuffled` to hold the result.
4. Iterate over the range from 0 to `n - 1`.
5. For each index `i`, append `cards[i]` and `cards[i + n]` to the `shuffled` list.
6. Return the `shuffled` list.

⚠️ Common Mistakes

  • Forgetting to calculate the midpoint correctly.
  • Attempting to access indices that are out of range.

I-mplement

Implement the code to solve the algorithm.

def shuffle(cards):
    n = len(cards) // 2
    shuffled = []
    
    for i in range(n):
        shuffled.append(cards[i])
        shuffled.append(cards[i + n])
    
    return shuffled
Clone this wiki locally