Codepath

Sort Performances by Type

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

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the input to the problem?
    • A: The input is an integer array performances, where each integer represents a performance type classified as either even (e.g., dance, music) or odd (e.g., drama, poetry).
  • Q: What is the output?
    • A: The output is an array where all the even-type performances appear at the beginning, followed by all the odd-type performances.
  • Q: Are there specific requirements for the order of even or odd performances?
    • A: No specific order is required among even or odd performances; they just need to be grouped together.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use two lists to separate even and odd performances as you iterate through the input array. After processing, concatenate the even and odd lists to produce the desired result.

1. Initialize two empty lists: `even_performances` and `odd_performances`.
2. Iterate through the `performances` array:
   1. If the current performance is even, append it to `even_performances`.
   2. If the current performance is odd, append it to `odd_performances`.
3. Concatenate `even_performances` with `odd_performances` to get the final result.
4. Return the concatenated list.

⚠️ Common Mistakes

  • Misclassifying performances as even or odd, leading to incorrect grouping.
  • Not properly concatenating the even and odd lists, which could result in an incorrectly ordered array.
  • Assuming that the order of elements matters within even or odd groups when it does not.

I-mplement

def sort_performances_by_type(performances):
    even_performances = []
    odd_performances = []

    for performance in performances:
        if performance % 2 == 0:
            even_performances.append(performance)
        else:
            odd_performances.append(performance)

    return even_performances + odd_performances

# Example usage
print(sort_performances_by_type([3, 1, 2, 4]))  # Output: [4, 2, 1, 3]
print(sort_performances_by_type([0]))           # Output: [0]
Fork me on GitHub