Unit 2 Session 1 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the problem asking for?
Q: What are the inputs?
signals
consisting of distinct strings.Q: What are the outputs?
Q: Are there any constraints on the values in the array?
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a dictionary to count occurrences of each string and its reverse to form pairs.
1. Initialize an empty dictionary `signal_count` to store the frequency of each string.
2. Initialize a variable `pair_count` to 0 to count the number of pairs.
3. Iterate through the `signals` array.
- For each string, calculate its reverse.
- If the reverse string exists in `signal_count` with a count greater than 0, form a pair, decrement the count, and increment `pair_count`.
- If the reverse string does not exist or its count is 0, add the string to `signal_count` or increment its count if it already exists.
4. Return the value of `pair_count`.
def max_number_of_string_pairs(signals):
signal_count = {}
pair_count = 0
for signal in signals:
reverse_signal = signal[::-1]
if reverse_signal in signal_count and signal_count[reverse_signal] > 0:
pair_count += 1
signal_count[reverse_signal] -= 1
else:
if signal in signal_count:
signal_count[signal] += 1
else:
signal_count[signal] = 1
return pair_count