Understand what the interviewer is asking for by using test cases and questions about the problem.
portals[i] + portals[j]
equals destination
.portals
and a digit string destination
.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a dictionary to store the frequency of each portal string, then iterate through the list and check for valid pairs.
1) Create a dictionary `portal_count` to store the frequency of each portal string.
2) Iterate through `portals` to populate the dictionary.
3) Iterate through `portals` again to count valid pairs:
- Calculate the required matching string for each portal.
- Check if the required string exists in the dictionary and update the count accordingly.
4) Return the total count of valid pairs.
⚠️ Common Mistakes
def num_of_time_portals(portals, destination):
# Create a dictionary to store the frequency of each portal string
portal_count = {}
for portal in portals:
if portal in portal_count:
portal_count[portal] += 1
else:
portal_count[portal] = 1
count = 0
# Iterate through each portal string
for portal in portals:
# Determine the required matching string
required = destination[len(portal):]
# Check if the required string exists in the dictionary
if required in portal_count:
# Decrease count if portal == required to avoid counting same index pairs
if portal == required:
count += portal_count[required] - 1
else:
count += portal_count[required]
return count