replaced double for-loops with HashSet and one for-each, upgraded complexity from O(n^2) to O(n)
import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; class Solution { public static int similarPairs(String[] words) { int num=0; Set<String> seenWords = new HashSet<>(); for (String word: words){ if (seenWords.contains(word)){ num++; } seenWords.add(word); } return num; } }
import org.junit.jupiter.api.Test;- import org.junit.jupiter.api.Test;
- import java.util.HashSet;
- import java.util.Set;
- class Solution {
- public static int similarPairs(String[] words) {
int num=0;for(int i=0; i<words.length; i++){for(int j=i+1; j<words.length; j++){if(words[i]==words[j])num+=1;- int num=0;
- Set<String> seenWords = new HashSet<>();
- for (String word: words){
- if (seenWords.contains(word)){
- num++;
- }
}- seenWords.add(word);
- }
- return num;
- }
- }