-
Notifications
You must be signed in to change notification settings - Fork 253
Encode
Raymond Chen edited this page Aug 1, 2024
·
6 revisions
"TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Arrays, String Manipulation, Indexing
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 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""
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
- Incorrectly accessing or modifying indices.
- Not handling the edge case where the message length is 1.
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)