The User Purchase Platform problem on LeetCode provides you with a set of user purchase records and asks you to analyze user purchasing behavior. Typically, you are given a list of users, their purchases (with timestamps and amounts), and possibly the platform (like 'web', 'mobile', etc.) from which the purchase was made.
The task is usually to answer questions like: Which users made purchases on multiple platforms? or Which users made their first purchase on the mobile platform? or For each user, return their earliest purchase per platform.
Constraints often include:
user_id
, purchase_time
, platform
, and amount
.To solve this problem, we need to identify users who have made purchases on more than one platform. The straightforward (brute-force) approach would be to, for each user, collect all the platforms they have used and count them. If a user's platform count is two or more, include them in the result.
The brute-force way would involve iterating through all records, grouping by user, and counting unique platforms. However, this can be inefficient for large datasets.
To optimize, we can use a hash map (dictionary) to map each user to a set of platforms they've used. This allows us to efficiently add platforms and check the count at the end.
This approach is analogous to making a list of all the stores you've shopped at: for each receipt, add the store to your list if it's not there already. At the end, count how many unique stores you have for each person.
Let's break down the solution step by step:
user_id
and the value is a set of platforms the user has made purchases on.
We use a set for each user because checking for uniqueness and adding a new platform is an O(1) operation, and avoids counting duplicate platforms.
Consider the following purchase records:
Step by step:
Brute-force Approach:
The optimized approach is much more efficient, especially for large datasets.
In this problem, we efficiently identified users who made purchases on at least two different platforms by leveraging a hash map with sets to track unique platforms per user. This strategy avoids unnecessary repeated work and allows for quick lookups and insertions. The key insight is to use data structures that fit the problem's requirements, leading to a clean and performant solution.
from collections import defaultdict
from typing import List, Dict
def users_with_multiple_platforms(purchases: List[Dict]) -> List[int]:
# purchases: List of dicts with keys: user_id, purchase_time, platform, amount
user_platforms = defaultdict(set)
for purchase in purchases:
user_platforms[purchase['user_id']].add(purchase['platform'])
result = [user_id for user_id, platforms in user_platforms.items() if len(platforms) >= 2]
return sorted(result)
#include <vector>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
using namespace std;
struct Purchase {
int user_id;
string purchase_time;
string platform;
double amount;
};
vector<int> usersWithMultiplePlatforms(const vector<Purchase>& purchases) {
unordered_map<int, unordered_set<string>> userPlatforms;
for (const auto& p : purchases) {
userPlatforms[p.user_id].insert(p.platform);
}
vector<int> result;
for (const auto& entry : userPlatforms) {
if (entry.second.size() >= 2) {
result.push_back(entry.first);
}
}
sort(result.begin(), result.end());
return result;
}
import java.util.*;
class Purchase {
int userId;
String purchaseTime;
String platform;
double amount;
public Purchase(int userId, String purchaseTime, String platform, double amount) {
this.userId = userId;
this.purchaseTime = purchaseTime;
this.platform = platform;
this.amount = amount;
}
}
public class Solution {
public List<Integer> usersWithMultiplePlatforms(List<Purchase> purchases) {
Map<Integer, Set<String>> userPlatforms = new HashMap<>();
for (Purchase p : purchases) {
userPlatforms
.computeIfAbsent(p.userId, k -> new HashSet<>())
.add(p.platform);
}
List<Integer> result = new ArrayList<>();
for (Map.Entry<Integer, Set<String>> entry : userPlatforms.entrySet()) {
if (entry.getValue().size() >= 2) {
result.add(entry.getKey());
}
}
Collections.sort(result);
return result;
}
}
function usersWithMultiplePlatforms(purchases) {
// purchases: Array of objects {user_id, purchase_time, platform, amount}
const userPlatforms = {};
purchases.forEach(purchase => {
if (!userPlatforms[purchase.user_id]) {
userPlatforms[purchase.user_id] = new Set();
}
userPlatforms[purchase.user_id].add(purchase.platform);
});
const result = [];
for (const userId in userPlatforms) {
if (userPlatforms[userId].size >= 2) {
result.push(Number(userId));
}
}
return result.sort((a, b) => a - b);
}