Graphs and String Manipulation - Medium LC

This problem is just laborious but requires a bit of work on Graphs (I usually build the graphs using Hashtables), traversal of graphs (in this case DFS) and string manipulation. Interesting that the standard String.CompareTo C# does not really compare lexicographically, at least when I used it, it failed for some test cases, so I had to build my own. Long code is down below, cheers, ACC.



1258. Synonymous Sentences
Medium

You are given a list of equivalent string pairs synonyms where synonyms[i] = [si, ti] indicates that si and ti are equivalent strings. You are also given a sentence text.

Return all possible synonymous sentences sorted lexicographically.

Example 1:

Input: synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]], text = "I am happy today but was sad yesterday"
Output: ["I am cheerful today but was sad yesterday","I am cheerful today but was sorrow yesterday","I am happy today but was sad yesterday","I am happy today but was sorrow yesterday","I am joy today but was sad yesterday","I am joy today but was sorrow yesterday"]

Example 2:

Input: synonyms = [["happy","joy"],["cheerful","glad"]], text = "I am happy today but was sad yesterday"
Output: ["I am happy today but was sad yesterday","I am joy today but was sad yesterday"]

Constraints:

  • 0 <= synonyms.length <= 10
  • synonyms[i].length == 2
  • 1 <= si.length,ti.length <= 10
  • si != ti
  • text consists of at most 10 words.
  • The words of text are separated by single spaces.

public IList GenerateSentences(IList> synonyms, string text)
{
 Hashtable htSynonyms = CreateSynonymsHashtable(synonyms);
 Hashtable listOfSynonyms = new Hashtable();
 string[] words = text.Split(' ');
 foreach (string w in words)
 {
 if (!listOfSynonyms.ContainsKey(w))
 {
 List synonymsForWord = new List();
 GenerateListSynonyms(w, htSynonyms, new Hashtable(), synonymsForWord);
 SortWordsLex(synonymsForWord);
 listOfSynonyms.Add(w, synonymsForWord);
 }
 }
 List retVal = new List();
 ProcessSynonyms(words, 0, "", listOfSynonyms, retVal);
 return retVal;
}
public void GenerateListSynonyms(string from,
 Hashtable map,
 Hashtable wordVisited,
 List synonyms)
{
 if (wordVisited.ContainsKey(from)) return;
 wordVisited.Add(from, true);
 synonyms.Add(from);
 if (map.ContainsKey(from))
 {
 Hashtable localSynonyms = (Hashtable)map[from];
 foreach (string word in localSynonyms.Keys)
 {
 GenerateListSynonyms(word, map, wordVisited, synonyms);
 }
 }
}
public int CompareLex(string s1, string s2)
{
 int index1 = 0;
 int index2 = 0;
 while (index1 < s1.Length && index2 < s2.Length) { if (s1[index1] == s2[index2]) { index1++; index2++; } else { return (s1[index1] < s2[index2]) ? -1 : 1; } } if (index1 == index2) return 0; return (index1 < index2) ? -1 : 1; } public void SortWordsLex(List words)
{
 bool sorted = false;
 while (!sorted)
 {
 sorted = true;
 for (int i = 0; i < words.Count - 1; i++) { if (CompareLex(words[i], words[i + 1])> 0)
 {
 sorted = false;
 string temp = words[i];
 words[i] = words[i + 1];
 words[i + 1] = temp;
 }
 }
 }
}
public Hashtable CreateSynonymsHashtable(IList> synonyms)
{
 Hashtable retVal = new Hashtable();
 foreach (List list in synonyms)
 {
 for (int i = 0; i < 2; i++) { if (!retVal.ContainsKey(list[i])) retVal.Add(list[i], new Hashtable()); Hashtable connections = (Hashtable)retVal[list[i]]; if (!connections.ContainsKey(list[(i + 1) % 2])) connections.Add(list[(i + 1) % 2], true); } } return retVal; } public void ProcessSynonyms(string[] wordsInText, int currentIndex, string currentText, Hashtable listOfSynonyms, List sentences)
{
 if (currentIndex>= wordsInText.Length)
 {
 sentences.Add(currentText.Trim());
 return;
 }
 string word = wordsInText[currentIndex];
 if (!listOfSynonyms.ContainsKey(word))
 {
 ProcessSynonyms(wordsInText, currentIndex + 1, currentText + " " + word, listOfSynonyms, sentences);
 }
 else
 {
 List listSynonyms = (List)listOfSynonyms[word];
 foreach (string w in listSynonyms)
 {
 ProcessSynonyms(wordsInText, currentIndex + 1, currentText + " " + w, listOfSynonyms, sentences);
 }
 }
}

Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...