737. Sentence similarity II

#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

// Maps each distinct word to a dense id so union-find can work on ints.
typedef struct {
  const char **keys;
  int *ids;
  int capacity;
  int size;
} WordIds;

static unsigned int hash_str(const char *s) {
  unsigned int h = 5381;
  while (*s)
    h = h * 33 + (unsigned char)*s++;
  return h;
}

static int word_id(WordIds *map, int *parent, const char *w) {
  unsigned int idx = hash_str(w) % map->capacity;
  while (map->keys[idx]) {
    if (!strcmp(map->keys[idx], w))
      return map->ids[idx];
    idx = (idx + 1) % map->capacity;
  }
  map->keys[idx] = w;
  map->ids[idx] = map->size;
  parent[map->size] = map->size;
  return map->size++;
}

static int find(int *parent, int x) {
  if (parent[x] != x)
    parent[x] = find(parent, parent[x]); // path compression
  return parent[x];
}

static void unite(int *parent, int a, int b) {
  parent[find(parent, a)] = find(parent, b);
}

bool areSentencesSimilarTwo(char **sentence1, int sentence1Size,
                            char **sentence2, int sentence2Size,
                            char ***similarPairs, int similarPairsSize,
                            int *similarPairsColSize) {
  (void)similarPairsColSize; // always 2
  if (sentence1Size != sentence2Size)
    return false;

  int maxWords = 2 * similarPairsSize + 2 * sentence1Size;
  WordIds map = {calloc(2 * maxWords + 1, sizeof(char *)),
                 malloc((2 * maxWords + 1) * sizeof(int)), 2 * maxWords + 1, 0};
  int *parent = malloc((maxWords + 1) * sizeof(int));

  for (int i = 0; i < similarPairsSize; i++)
    unite(parent, word_id(&map, parent, similarPairs[i][0]),
          word_id(&map, parent, similarPairs[i][1]));

  bool similar = true;
  for (int i = 0; i < sentence1Size && similar; i++) {
    const char *w1 = sentence1[i];
    const char *w2 = sentence2[i];
    if (strcmp(w1, w2) && find(parent, word_id(&map, parent, w1)) !=
                              find(parent, word_id(&map, parent, w2)))
      similar = false;
  }

  free(map.keys);
  free(map.ids);
  free(parent);
  return similar;
}
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;

class Solution {
  unordered_map<string, string> parent;

  string find(const string &w) {
    if (!parent.count(w))
      parent[w] = w;
    if (parent[w] != w)
      parent[w] = find(parent[w]); // path compression
    return parent[w];
  }

  void unite(const string &a, const string &b) { parent[find(a)] = find(b); }

public:
  bool areSentencesSimilarTwo(vector<string> &sentence1,
                              vector<string> &sentence2,
                              vector<vector<string>> &similarPairs) {
    if (sentence1.size() != sentence2.size())
      return false;

    for (const auto &p : similarPairs)
      unite(p[0], p[1]);

    for (size_t i = 0; i < sentence1.size(); i++) {
      if (sentence1[i] != sentence2[i] && find(sentence1[i]) != find(sentence2[i]))
        return false;
    }

    return true;
  }
};
package solution

func areSentencesSimilarTwo(sentence1 []string, sentence2 []string, similarPairs [][]string) bool {
    if len(sentence1) != len(sentence2) {
        return false
    }

    parent := make(map[string]string)

    var find func(w string) string
    find = func(w string) string {
        if _, ok := parent[w]; !ok {
            parent[w] = w
        }
        if parent[w] != w {
            parent[w] = find(parent[w]) // path compression
        }
        return parent[w]
    }

    unite := func(a, b string) {
        parent[find(a)] = find(b)
    }

    for _, p := range similarPairs {
        unite(p[0], p[1])
    }

    for i, w1 := range sentence1 {
        w2 := sentence2[i]
        if w1 != w2 && find(w1) != find(w2) {
            return false
        }
    }

    return true
}
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Solution {
    private final Map<String, String> parent = new HashMap<>();

    private String find(String w) {
        parent.putIfAbsent(w, w);
        if (!parent.get(w).equals(w)) {
            parent.put(w, find(parent.get(w))); // path compression
        }
        return parent.get(w);
    }

    private void unite(String a, String b) {
        parent.put(find(a), find(b));
    }

    public boolean areSentencesSimilarTwo(String[] sentence1, String[] sentence2, List<List<String>> similarPairs) {
        if (sentence1.length != sentence2.length) {
            return false;
        }

        for (List<String> p : similarPairs) {
            unite(p.get(0), p.get(1));
        }

        for (int i = 0; i < sentence1.length; i++) {
            String w1 = sentence1[i];
            String w2 = sentence2[i];
            if (!w1.equals(w2) && !find(w1).equals(find(w2))) {
                return false;
            }
        }

        return true;
    }
}
/**
 * @param {string[]} sentence1
 * @param {string[]} sentence2
 * @param {string[][]} similarPairs
 * @return {boolean}
 */
var areSentencesSimilarTwo = function (sentence1, sentence2, similarPairs) {
  if (sentence1.length !== sentence2.length) {
    return false;
  }

  const parent = new Map();

  const find = (w) => {
    if (!parent.has(w)) parent.set(w, w);
    if (parent.get(w) !== w) parent.set(w, find(parent.get(w))); // path compression
    return parent.get(w);
  };

  const unite = (a, b) => parent.set(find(a), find(b));

  for (const [a, b] of similarPairs) {
    unite(a, b);
  }

  for (let i = 0; i < sentence1.length; i++) {
    const w1 = sentence1[i];
    const w2 = sentence2[i];
    if (w1 !== w2 && find(w1) !== find(w2)) {
      return false;
    }
  }

  return true;
};
class Solution:
    def areSentencesSimilarTwo(
        self, sentence1: list[str], sentence2: list[str], similarPairs: list[list[str]]
    ) -> bool:
        if len(sentence1) != len(sentence2):
            return False

        parent: dict[str, str] = {}

        def find(w: str) -> str:
            parent.setdefault(w, w)
            if parent[w] != w:
                parent[w] = find(parent[w])  # path compression
            return parent[w]

        def unite(a: str, b: str) -> None:
            parent[find(a)] = find(b)

        for a, b in similarPairs:
            unite(a, b)

        return all(w1 == w2 or find(w1) == find(w2) for w1, w2 in zip(sentence1, sentence2))
use std::collections::HashMap;

struct UnionFind<'a> {
    parent: HashMap<&'a str, &'a str>,
}

impl<'a> UnionFind<'a> {
    fn find(&mut self, w: &'a str) -> &'a str {
        let p = *self.parent.entry(w).or_insert(w);
        if p == w {
            return w;
        }
        let root = self.find(p);
        self.parent.insert(w, root); // path compression
        root
    }

    fn unite(&mut self, a: &'a str, b: &'a str) {
        let (ra, rb) = (self.find(a), self.find(b));
        self.parent.insert(ra, rb);
    }
}

impl Solution {
    pub fn are_sentences_similar_two(
        sentence1: Vec<String>,
        sentence2: Vec<String>,
        similar_pairs: Vec<Vec<String>>,
    ) -> bool {
        if sentence1.len() != sentence2.len() {
            return false;
        }

        let mut uf = UnionFind { parent: HashMap::new() };
        for p in &similar_pairs {
            uf.unite(&p[0], &p[1]);
        }

        sentence1
            .iter()
            .zip(&sentence2)
            .all(|(w1, w2)| w1 == w2 || uf.find(w1) == uf.find(w2))
    }
}

struct Solution;