LeetCode 1264: Page Recommendations
Problem Description
Explanation:
To solve this problem, we can use a graph-based approach where each user is represented as a node and the connections between users represent the pages they have in common. We can then traverse the graph starting from the given user and recommend pages based on the pages visited by the user's connections.
- Create a graph where each user is a node and the connections between users represent the common pages they have visited.
- Traverse the graph starting from the given user and recommend pages based on the pages visited by the user's connections.
- Keep track of the recommended pages and their frequencies.
- Return the top k recommended pages based on their frequencies.
Time Complexity: O(V + ElogE) where V is the number of users and E is the number of edges (connections between users). Sorting the recommended pages takes O(ElogE) time. Space Complexity: O(V + E) for storing the graph and recommended pages.
:
Solutions
import java.util.*;
class Solution {
public List<Integer> pagesRecommendations(int[][] users, int user, int k) {
Map<Integer, Set<Integer>> graph = new HashMap<>();
for (int[] u : users) {
for (int page : u) {
graph.putIfAbsent(page, new HashSet<>());
graph.get(page).addAll(Arrays.stream(u).boxed().collect(Collectors.toSet()));
}
}
Set<Integer> visited = new HashSet<>();
visited.addAll(Arrays.stream(users[user]).boxed().collect(Collectors.toSet()));
Map<Integer, Integer> recommendedPages = new HashMap<>();
for (int connectedPage : graph.get(users[user][0])) {
if (!visited.contains(connectedPage)) {
recommendedPages.put(connectedPage, recommendedPages.getOrDefault(connectedPage, 0) + 1);
}
}
List<Integer> result = new ArrayList<>(recommendedPages.keySet());
result.sort((a, b) -> recommendedPages.get(b) - recommendedPages.get(a));
return result.subList(0, Math.min(k, result.size()));
}
}
Loading editor...