Codepath

Encode

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

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: Arrays, String Manipulation, Indexing

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 function?

    • A: The input is a string message and an integer array indices of the same length as message.
  • Q: What is the expected output of the function?

    • A: The function should return a new string where each character from message is placed at the position specified by indices.
  • Q: What does the indices array represent?

    • A: The indices array indicates the target position for each character in the message. The character at index i in message will move to the position indices[i] in the output string.
  • Q: Are there any constraints on the input?

    • A: The length of message and indices are guaranteed to be equal, and each index in indices is unique and within the bounds of the string.
  • The function shuffle() should take a string message and an integer array indices and return a shuffled version of the string where each character in message is moved to the position specified by indices.

HAPPY CASE
Input: message = "evil", indices = [3,1,2,0]
Expected Output: "lvie"

Input: message = "findme", indices = [0,1,2,3,4,5]
Expected Output: "findme"

EDGE CASE
Input: message = "a", indices = [0]
Expected Output: "a"

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Initialize an empty list of the same length as the message, then place each character in the new list at the index specified by indices. Finally, join the list into a string.

1. Initialize a list `shuffled_message` with empty strings of the same length as `message`.
2. Iterate through each character in `message` using its index `i`.
    a. Place the character `message[i]` at the position `indices[i]` in `shuffled_message`.
3. Join the list `shuffled_message` into a single string.
4. Return the joined string

⚠️ Common Mistakes

  • Incorrectly accessing or modifying indices.
  • Not handling the edge case where the message length is 1.

I-mplement

Implement the code to solve the algorithm.

def shuffle(message, indices):
    # Initialize a list to store the shuffled characters
    shuffled_message = [''] * len(message)
    
    # Place each character at the corresponding position
    for i in range(len(message)):
        shuffled_message[indices[i]] = message[i]
    
    # Join the list into a string and return it
    return ''.join(shuffled_message)
Fork me on GitHub