#585
Investments in 2016
MediumDatabaseHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses hash maps to efficiently track the counts of tiv_2015 values and unique locations. This reduces the need for nested loops, allowing us to process the data in a single pass.
⚙️
Algorithm
5 steps- 1Step 1: Create a hash map to count occurrences of each tiv_2015 value.
- 2Step 2: Create a set to track unique (lat, lon) pairs.
- 3Step 3: Iterate through the insurance records to populate the hash map and set.
- 4Step 4: Iterate through the records again to sum tiv_2016 values for those with matching tiv_2015 and unique locations.
- 5Step 5: Round the total sum to two decimal places and return it.
solution.py11 lines
1# Full working Python code
2import pandas as pd
3
4def investment_sum(insurances):
5 tiv_count = insurances['tiv_2015'].value_counts()
6 unique_locations = set((insurances['lat'][i], insurances['lon'][i]) for i in range(len(insurances)))
7 total = 0.0
8 for i in range(len(insurances)):
9 if tiv_count[insurances['tiv_2015'][i]] > 1 and (insurances['lat'][i], insurances['lon'][i]) in unique_locations:
10 total += insurances['tiv_2016'][i]
11 return round(total, 2)ℹ
Complexity note: The time complexity is O(n) because we are iterating through the records a constant number of times. The space complexity is O(n) due to the storage of counts and unique locations in hash maps and sets.
- 1Using hash maps can significantly reduce time complexity.
- 2Understanding unique constraints is crucial for filtering results.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.