LeetCode 1794: Count Pairs of Equal Substrings With Minimum Difference
Problem Description
Explanation:
This problem asks us to find the count of pairs of equal substrings with the minimum difference between their indices. We need to count the number of pairs of substrings where the difference between their indices is minimized.
To solve this problem, we can iterate through all possible pairs of substrings and keep track of the minimum difference between their indices. We can use a hashmap to store the indices of each substring, and then for each pair of substrings, calculate the difference between their indices and update the minimum difference.
Here is the detailed algorithm:
- Initialize a hashmap to store the indices of each substring.
- Initialize a variable to keep track of the minimum difference between the indices of equal substrings.
- Iterate through all possible pairs of substrings.
- For each pair of substrings, calculate the difference between their indices.
- If the difference is less than the current minimum difference, update the minimum difference.
- Finally, return the count of pairs of substrings with the minimum difference between their indices.
Time Complexity: O(n^2) - where n is the length of the input string Space Complexity: O(n)
: :
Solutions
class Solution {
public int countSubstrings(String s) {
int count = 0;
Map<String, List<Integer>> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j <= s.length(); j++) {
String sub = s.substring(i, j);
map.putIfAbsent(sub, new ArrayList<>());
map.get(sub).add(i);
}
}
int minDiff = Integer.MAX_VALUE;
for (List<Integer> indices : map.values()) {
if (indices.size() > 1) {
for (int i = 0; i < indices.size(); i++) {
for (int j = i + 1; j < indices.size(); j++) {
minDiff = Math.min(minDiff, Math.abs(indices.get(i) - indices.get(j)));
}
}
}
}
for (List<Integer> indices : map.values()) {
if (indices.size() > 1) {
for (int i = 0; i < indices.size(); i++) {
for (int j = i + 1; j < indices.size(); j++) {
if (Math.abs(indices.get(i) - indices.get(j)) == minDiff) {
count++;
}
}
}
}
}
return count;
}
}
Loading editor...