714140. Anagrams in Linked List
Medium
Anagrams in Linked List
Summary
Given a linked list and a target anagram, find all occurrences of the target anagram within the linked list. This problem involves manipulating a linked list while keeping track of character frequencies to identify anagrams.
Detailed Explanation
To solve this problem, we can use a sliding window approach. We maintain a frequency map for the target anagram and slide a window over the linked list to find matches. Here's a step-by-step breakdown:
- Initialize an empty frequency map
freqMapwith character frequencies for the target anagram. - Iterate through the linked list, maintaining a sliding window of size equal to the length of the target anagram.
- For each node in the window:
- Update the frequency map by incrementing the count for each character in the current node's value.
- If the frequency map matches the original
freqMap, we have found a match and add it to our result list.
- Continue iterating until the end of the linked list is reached.
Time complexity: O(n), where n is the length of the linked list, since we only iterate through the list once.
Space complexity: O(1), as we maintain a fixed-size frequency map.
Here's an ASCII art diagram to illustrate the sliding window approach:
+---------------+
| A | B | C |
+---------------+
^
| Window of size 3
v
+---------------+
| D | E | F |
+---------------+
Optimized Solutions
Java
public class Solution {
public List<String> findAnagrams(ListNode head, String target) {
Map<Character, Integer> freqMap = new HashMap<>();
for (char c : target.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
List<String> result = new ArrayList<>();
ListNode current = head;
while (current != null) {
Map<Character, Integer> windowFreqMap = new HashMap<>(freqMap);
for (int i = 0; i < target.length(); i++) {
char c = current.val.charAt(i);
windowFreqMap.put(c, windowFreqMap.getOrDefault(c, 0) - 1);
if (windowFreqMap.equals(freqMap)) {
result.add(current.val.substring(0, target.length()));
}
}
current = current.next;
}
return result;
}
}