question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
top-k-frequent-elements | K pattern - heaps/Priority 3 solutions Frequency Map, Bucket Sort, PriorityQueue | k-pattern-heapspriority-3-solutions-freq-pw1q | 215. Kth Largest Element in an Array same pattern\n451. Sort Characters By Frequency\n703. Kth Largest Element in a Stream\n767. Reorganize String\nRearrange St | Dixon_N | NORMAL | 2024-05-23T05:59:07.844979+00:00 | 2024-06-09T13:11:48.216080+00:00 | 1,651 | false | [215. Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/solutions/5195848/k-pattern-heaps-peiority/) same pattern\n451. Sort Characters By Frequency\n[703. Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/solutions/5198578/k-pattern/)\n[767. Reorganize String](https://leetcode.com/problems/reorganize-string/solutions/5196813/k-pattern/)\nRearrange String k Distance Apart -- Q & A below\n[1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows](https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/solutions/5198589/k-pattern/)\n[373. Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/solutions/5197679/the-k-pattern/)\n[378. Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/solutions/5197755/the-k-pattern/)\n[719. Find K-th Smallest Pair Distance]()\n[2040. Kth Smallest Product of Two Sorted Arrays]()\n[264. Ugly Number II](https://leetcode.com/problems/ugly-number-ii/solutions/5198107/nthuglynumber/)\n[263. Ugly Number](https://leetcode.com/problems/ugly-number/solutions/5198605/the-ugly-number/)\n[502. IPO](https://leetcode.com/problems/ipo/solutions/5198438/priorityqueue-pattern/)\n# Code\n```java []\n\n//Frequency Map\n\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map<Integer, Integer> frequencyMap = new HashMap<>();\n \n for (int n : nums) {\n frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);\n }\n \n List<Map.Entry<Integer, Integer>> entryList = new ArrayList<>(frequencyMap.entrySet());\n \n Collections.sort(entryList, (a, b) -> b.getValue()- a.getValue());\n \n int[] result = new int[k];\n for (int i = 0; i < k; i++) {\n result[i] = entryList.get(i).getKey();\n }\n \n return result;\n }\n}\n```\n```java []\n// Bucket Sort\n\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n \n\n HashMap<Integer, Integer> hm = new HashMap<>();\n for (int i: nums){\n hm.put(i,hm.getOrDefault(i,0)+1);\n }\n List<Integer> [] list = new List[nums.length+1];\n for(int key : hm.keySet()){\n int frequency = hm.get(key);\n if(list[frequency]==null){ list[frequency]= new ArrayList<>();}\n list[frequency].add(key);\n }\n\n int index =0;\n int [] res = new int [k];\n for(int pos = list.length-1; pos>=0 && index<k ; pos--){\n if(list[pos]!=null){\n for(int i: list[pos]){\n res[index++] = i;\n if(index==k) break; \n }\n }\n }\n return res;\n }\n}\n```\n```java []\n//PriorityQueue\n// same as 215. Kth Largest Element in an Array\n\n//PriorityQueue\n// same as 215. Kth Largest Element in an Array\n\npublic class Solution {\n public int[] topKFrequent(int[] nums, int k) {\n // Step 1: Count the frequency of each element\n Map<Integer, Integer> frequencyMap = new HashMap<>();\n for (int num : nums) {\n frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);\n }\n\n // Step 2: Use a PriorityQueue (min-heap) to keep track of the top k elements\n PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(\n (a, b) -> Integer.compare(a.getValue(),b.getValue())\n );\n\n // Step 3: Maintain the size of the heap\n for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {\n minHeap.offer(entry);\n if (minHeap.size() > k) {\n minHeap.poll();\n }\n }\n\n // Step 4: Extract the results from the heap\n int[] result = new int[k];\n int index = 0;\n while (!minHeap.isEmpty()) {\n result[index++] = minHeap.poll().getKey();\n }\n\n return result;\n }\n}\n\n```\n\n\n### Rearrange String k Distance Apart\n```java []\n/*\nProblem statement\n\nSome time ago, Ninja found an entertaining string \u2018S\u2019 consisting of only lowercase English letters.\nBut he did not like the string if two same characters are not \u2018K\u2019 distant apart.\n\nHe wants your help to know whether it is possible to rearrange the string\u2019s characters\nsuch that all two similar characters are at least \u2018K\u2019 distance apart.\n\nReturn 1 if it is possible to make such string else return 0.\n\nFor example: Let \u2018S\u2019 = \u201Caabc\u201D and \u2018K\u2019 = 1, then we need to rearrange \u2018S\u2019 as two \u2018a\u2019 are not \u2018K\u2019 distance apart, after rearranging we can write \u201Cabac\u201D or \u201Cabca\u201D and return 1.\n\nDetailed explanation ( Input/output format, Notes, Images )\nConstraints :\n1 <= T <= 5\n1 <= N <= 5000\n1 <= K <= N\n\nWhere \u2018N\u2019 is the length of the string \u2018S\u2019.\n\nTime limit: 1 sec\nNote :\n\nYou do not need to print anything. It has already been taken care of. Just implement the given function.\nSample Input 1 :\n2\n1\naabbcc\n2\nabcccd\nSample Output 1 :\n1\n1\nExplanation of Sample Output 1 :\nTest Case 1: We can rearrange \u201Caabbcc\u201D as \u201Ccbacba\u201D all the same characters are at least one distance apart and return 1. \n\nTest Case 2: We can rearrange \u201Cabcccd\u201D as \u201Ccdcbca\u201D all the same characters are at least 2 distance apart and return 1. \nSample Input 2 :\n2\n3\naaacccb\n2\naaczcbcab\nSample Output 2 :\n0\n1\n*/\n\nimport java.util.*;\n\npublic class Solution {\n public static int favString(String s, int k) {\n // Length of the input string\n int stringLength = s.length();\n\n // Map to keep track of character counts\n Map<Character, Integer> charCounts = new HashMap<>();\n\n // Count the frequency of each character in the string\n for (char ch : s.toCharArray()) {\n charCounts.put(ch, charCounts.getOrDefault(ch, 0) + 1);\n }\n\n // Priority Queue to store character frequencies and sort them in descending order\n PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<>(\n (a, b) -> b.getValue() - a.getValue()\n );\n maxHeap.addAll(charCounts.entrySet());\n\n // Queue to keep track of characters used in the last k positions\n Deque<Map.Entry<Character, Integer>> queue = new ArrayDeque<>();\n\n // StringBuilder to build the result string\n StringBuilder result = new StringBuilder();\n\n // Loop until the Priority Queue is empty\n while (!maxHeap.isEmpty()) {\n Map.Entry<Character, Integer> current = maxHeap.poll(); // Get the most frequent remaining character\n char ch = current.getKey();\n int count = current.getValue();\n\n // Add the character to the result if count is greater than 0\n if (count > 0) {\n result.append(ch);\n current.setValue(count - 1);\n queue.offer(current);\n }\n\n // If there are k elements in queue, it\'s time to release the front element\n if (queue.size() >= k) {\n Map.Entry<Character, Integer> front = queue.pollFirst();\n if (front.getValue() > 0) {\n // If it still has remaining count, add it back to the Priority Queue\n maxHeap.offer(front);\n }\n }\n }\n return result.length() == stringLength ? 1 : 0;\n }\n}\n\n``` | 9 | 0 | ['Array', 'Hash Table', 'Divide and Conquer', 'Sorting', 'Heap (Priority Queue)', 'Bucket Sort', 'Counting', 'Java'] | 2 |
top-k-frequent-elements | Easy Java solution with drawing explanation - TC = O(n log k) | easy-java-solution-with-drawing-explanat-atdx | Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n\n\n\n\n# Complexity\n- Time complexity: O(n log k)\n Add your time complexity here | sopheary | NORMAL | 2023-07-03T22:29:17.102613+00:00 | 2023-07-05T00:00:08.893888+00:00 | 1,858 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n\n\n\n# Complexity\n- Time complexity: O(n log k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the given code is O(n log k), where n represents the total number of elements in the input array and k represents the value of the parameter k.\n\nHere\'s a breakdown of the time complexity analysis for each part of the code:\n\nCreating a frequency map (HashMap): This loop iterates over the nums array, which contains n elements. The put operation in the HashMap takes constant time on average, so the overall time complexity is O(n).\n\nCreating a priority queue (PriorityQueue): This loop iterates over the entries in the map, which contains at most n elements. Adding an entry to the priority queue has a time complexity of O(log k), where k is the maximum size of the priority queue. In this case, k represents the parameter provided to the topKFrequent method. Therefore, the overall time complexity for this part is O(n log k).\n\nExtracting top k elements from the priority queue: This loop executes k times, and each iteration involves calling poll on the priority queue, which has a time complexity of O(log k). As a result, the time complexity for this part is O(k log k).\n\nOverall, the dominant factor in the time complexity is the creation of the priority queue, which gives us a total time complexity of O(n log k) for the given code.\n\n# Code\n```\nclass Solution {\n public int[] topKFrequent(int[] nums, int k) {\n int result[] = new int[k];\n\n Map<Integer,Integer> map = new HashMap<>();\n for(int i: nums){\n map.put(i, map.getOrDefault(i,0) + 1);\n }\n\n PriorityQueue<Map.Entry<Integer,Integer>> pq = \n new PriorityQueue<>((a,b) -> b.getValue() - a.getValue());\n\n for(Map.Entry<Integer,Integer> entry: map.entrySet()){\n pq.add(entry);\n }\n\n for(int i=0; i<k; i++){\n result[i] = pq.poll().getKey();\n }\n\n return result;\n \n }\n}\n``` | 9 | 0 | ['Heap (Priority Queue)', 'Java'] | 4 |
top-k-frequent-elements | Bucket sort, O(n) with explanation | bucket-sort-on-with-explanation-by-dzmtr-x8dw | Knowing that max frequency is nums.size (all elements are the same), we can put elements in array, according to their count.\n\nExample:\n[1, 1, 1, 2, 2, 3]\n\n | dzmtr | NORMAL | 2023-05-22T10:11:18.184990+00:00 | 2023-05-22T10:12:01.314603+00:00 | 993 | false | Knowing that max frequency is nums.size (all elements are the same), we can put elements in array, according to their count.\n\nExample:\n[1, 1, 1, 2, 2, 3]\n\nstore their count in a Map <Element: Count>:\n[{1: 3}, {2: 2}, {3: 1}]\n\nput them in freq Array<Count: List<Element>>:\n[[], [3], [2], [1], [], [], []]\n\nSince we need most frequent elements, flat the array and return sublist of k size, starting from the end. \n\nTime: O(n)\nSpace: O(n)\n\n```\nclass Solution {\n fun topKFrequent(nums: IntArray, k: Int): IntArray {\n val map = nums.toList().groupingBy { it }.eachCount() // O(n)\n\n val freq = Array<MutableList<Int>>(nums.size + 1) { mutableListOf() } // [freq : elements]\n map.forEach { k,v -> freq[v].add(k) }\n \n return freq.flatMap{ it }.takeLast(k).toIntArray()\n }\n}\n``` | 9 | 0 | ['Bucket Sort', 'Kotlin'] | 2 |
top-k-frequent-elements | [TypeScript]: Frequency count and then sort (Runtime 97%, Memory 70%) | typescript-frequency-count-and-then-sort-2dp3 | Intuition\n Describe your first thoughts on how to solve this problem. \nFirst we count the frequency of unique items, and then we return the most frequent ones | luzede | NORMAL | 2023-05-22T09:55:53.927024+00:00 | 2023-05-22T09:55:53.927048+00:00 | 4,264 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst we count the frequency of unique items, and then we return the most frequent ones.\n\n# Complexity\n- Time complexity: $$O(n*logn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```TypeScript\nfunction topKFrequent(nums: number[], k: number): number[] {\n const freq: { [key: number]: number } = {};\n for (const n of nums) {\n if (freq[n] === undefined) freq[n] = 0;\n freq[n] += 1;\n }\n return Object.entries(freq)\n .sort((a, b) => b[1] - a[1])\n .slice(0, k)\n .map(v => Number(v[0]));\n};\n``` | 9 | 0 | ['Array', 'Hash Table', 'Sorting', 'Counting', 'TypeScript'] | 2 |
top-k-frequent-elements | [Python3] Sort - Heap - Quick Select | python3-sort-heap-quick-select-by-dolong-0nes | Intuition\nThe Problem finding the k-th smallest or largest of something can be solved and optimized follows this order: sorting -> heap -> quick select\n Descr | dolong2110 | NORMAL | 2023-04-22T08:56:26.214705+00:00 | 2023-04-22T08:56:26.214753+00:00 | 2,601 | false | # Intuition\nThe Problem finding the k-th smallest or largest of something can be solved and optimized follows this order: sorting -> heap -> quick select\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n###### 1. Sorting\n```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n if k == len(nums): return nums\n c = collections.Counter(nums)\n d = [(c[key], key) for key in c]\n d.sort(reverse=True)\n return [p[1] for p in d[:k]]\n```\n- TC: $$O(nlogn)$$\n- SC: $$O(n)$$\n###### 2. Heap\n```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n if k == len(nums): return nums\n c = collections.Counter(nums)\n d = [(c[key], key) for key in c]\n\n max_heap = d[:k]\n heapq.heapify(max_heap)\n for i in range(k, len(d)):\n heapq.heappushpop(max_heap, d[i])\n return [val[1] for val in max_heap]\n```\n- TC: $$O(nlogk)$$\n- SC: $$O(n)$$\n###### 3. Quick Select\n```\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n if k == len(nums): return nums\n c = collections.Counter(nums)\n d = [(c[key], key) for key in c]\n \n def partition(l: int, r: int, p: int) -> int:\n pivot = d[p]\n d[p], d[r] = d[r], d[p]\n new_idx = l\n for i in range(l, r):\n if d[i][0] < pivot[0]:\n d[i], d[new_idx] = d[new_idx], d[i]\n new_idx += 1\n d[r], d[new_idx] = d[new_idx], d[r]\n return new_idx\n\n def select(l: int, r: int, k: int) -> int:\n if l == r: return l\n p = random.randint(l, r)\n p = partition(l, r, p)\n if p < k: return select(p + 1, r, k)\n elif p > k: return select(l, p - 1, k)\n else: return p\n\n return [p[1] for p in d[select(0, len(d) - 1, len(d) - k):]]\n```\n- TC: $$O(n)$$ on average\n- SC: $$O(n)$$ | 9 | 0 | ['Divide and Conquer', 'Sorting', 'Heap (Priority Queue)', 'Quickselect', 'Python3'] | 0 |
top-k-frequent-elements | [Rust] 0ms - Count Frequency + Sort By Frequency | rust-0ms-count-frequency-sort-by-frequen-pdkp | rust\nimpl Solution {\n pub fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> {\n let mut map = HashMap::new();\n nums.into_iter()\n | kurosuha | NORMAL | 2022-04-09T08:22:12.055188+00:00 | 2022-04-09T08:22:12.055223+00:00 | 411 | false | ```rust\nimpl Solution {\n pub fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> {\n let mut map = HashMap::new();\n nums.into_iter()\n .for_each(|num| *map.entry(num).or_insert(0) += 1);\n let mut vec: Vec<(i32, i32)> = map.into_iter().collect();\n vec.sort_by(|a, b| b.1.cmp(&a.1));\n vec.iter().take(k as usize).map(|x| x.0).collect()\n }\n}\n``` | 9 | 0 | ['Rust'] | 1 |
top-k-frequent-elements | C++ unordered_map & priority_queue - solved live on stream | c-unordered_map-priority_queue-solved-li-lsx2 | We practice algos everyday at 6pm PT. Check my profile for the stream.\n\nTime Complexity: O(nlogn)\nSpace Complexity: O(n)\n\n\nclass Solution {\npublic:\n | midnightsimon | NORMAL | 2022-04-09T01:19:29.235763+00:00 | 2022-04-09T01:19:29.235788+00:00 | 1,094 | false | We practice algos everyday at 6pm PT. Check my profile for the stream.\n\nTime Complexity: O(nlogn)\nSpace Complexity: O(n)\n\n```\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n \n //get a count of frequencies\n unordered_map<int, int> freqMap;\n for(int x : nums) {\n freqMap[x]++;\n }\n \n auto comp = [&freqMap](auto& lhs, auto&rhs) {\n return freqMap[lhs] > freqMap[rhs];\n };\n priority_queue<int, vector<int>, decltype(comp)> pq(comp);\n \n for(auto& thing : freqMap) {\n pq.push(thing.first);\n if(pq.size() > k) {\n pq.pop();\n }\n }\n\n vector<int> ans;\n while(!pq.empty()) {\n ans.push_back(pq.top());\n pq.pop();\n }\n \n return ans;\n }\n};\n``` | 9 | 0 | [] | 1 |
top-k-frequent-elements | C++ Solution Priority Queue, map Easy | c-solution-priority-queue-map-easy-by-hi-sunr | \n\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n priority_queue<pair<int, int>> pq;\n unordered_map<int | hitengoyal18 | NORMAL | 2020-12-11T12:58:16.708393+00:00 | 2020-12-11T12:58:16.708428+00:00 | 1,037 | false | ```\n\nclass Solution {\npublic:\n vector<int> topKFrequent(vector<int>& nums, int k) {\n priority_queue<pair<int, int>> pq;\n unordered_map<int, int>mp;\n vector<int> res;\n for(int i=0;i<nums.size();i++)\n mp[nums[i]] += 1; \n \n for (auto i : mp)\n pq.push(make_pair(i.second, i.first));\n \n for(int i=0;i<k;i++){\n res.push_back(pq.top().second);\n pq.pop();\n }\n return res;\n }\n};\n``` | 9 | 1 | ['C', 'Heap (Priority Queue)'] | 3 |
top-k-frequent-elements | [Go] 8ms, using PriorityQueue | go-8ms-using-priorityqueue-by-nakabonne-hcxa | We can build a priority queue with the heap package:\n\nfunc topKFrequent(nums []int, k int) []int {\n\tseen := make(map[int]int)\n\tfor _, n := range nums {\n\ | nakabonne | NORMAL | 2020-02-24T07:45:17.043089+00:00 | 2020-02-24T07:59:14.949508+00:00 | 2,391 | false | We can build a priority queue with the [heap](https://golang.org/pkg/container/heap/) package:\n```\nfunc topKFrequent(nums []int, k int) []int {\n\tseen := make(map[int]int)\n\tfor _, n := range nums {\n\t\tseen[n]++\n\t}\n\n\tq := &priorityQueue{}\n\theap.Init(q)\n\tfor val, cnt := range seen {\n\t\theap.Push(q, element{value: val, count: cnt})\n\t\tif q.Len() > k {\n\t\t\theap.Pop(q)\n\t\t}\n\t}\n\n\tans := make([]int, k, k)\n\tfor i := 1; i <= k; i++ {\n\t\tv := heap.Pop(q)\n\t\tif s, ok := v.(element); ok {\n\t\t\tans[k-i] = s.value\n\t\t}\n\t}\n\treturn ans\n}\n\ntype element struct {\n\tvalue int\n\tcount int\n}\n\ntype priorityQueue []element\n\nfunc (q priorityQueue) Len() int { return len(q) }\nfunc (q priorityQueue) Less(i, j int) bool { return q[i].count < q[j].count }\nfunc (q priorityQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\n\nfunc (q *priorityQueue) Push(x interface{}) {\n\t*q = append(*q, x.(element))\n}\n\nfunc (q *priorityQueue) Pop() interface{} {\n\told := *q\n\tn := len(old)\n\tx := old[n-1]\n\t*q = old[0 : n-1]\n\treturn x\n}\n\n``` | 9 | 0 | ['Go'] | 1 |
word-ladder-ii | C++ solution using standard BFS method, no DFS or backtracking | c-solution-using-standard-bfs-method-no-4v36i | I have struggled with this problem for a long time because nearly all the solution on the web is too long or too tricky and can hardly be remembered during the | antdavid | NORMAL | 2016-09-09T21:16:23.428000+00:00 | 2018-10-24T13:44:39.967281+00:00 | 78,934 | false | I have struggled with this problem for a long time because nearly all the solution on the web is too long or too tricky and can hardly be remembered during the interview.\n\nIn fact, this problem can be solved with a very standard BFS process, whose structure could haven been written by you for many many times (using while loop and a queue).\nThe following code is written in a very standard BFS method, which is easy to memorize. \n\nThe only tricky thing you need to remember is this is a BFS of paths not words!\nSo the element is the queue is a vector. That's it.\n\n```\n vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {\n //very interesting problem\n //It can be solved with standard BFS. The tricky idea is doing BFS of paths instead of words!\n //Then the queue becomes a queue of paths.\n vector<vector<string>> ans;\n queue<vector<string>> paths;\n wordList.insert(endWord);\n paths.push({beginWord});\n int level = 1;\n int minLevel = INT_MAX;\n \n //"visited" records all the visited nodes on this level\n //these words will never be visited again after this level \n //and should be removed from wordList. This is guaranteed\n // by the shortest path.\n unordered_set<string> visited; \n \n while (!paths.empty()) {\n vector<string> path = paths.front();\n paths.pop();\n if (path.size() > level) {\n //reach a new level\n for (string w : visited) wordList.erase(w);\n visited.clear();\n if (path.size() > minLevel)\n break;\n else\n level = path.size();\n }\n string last = path.back();\n //find next words in wordList by changing\n //each element from 'a' to 'z'\n for (int i = 0; i < last.size(); ++i) {\n string news = last;\n for (char c = 'a'; c <= 'z'; ++c) {\n news[i] = c;\n if (wordList.find(news) != wordList.end()) {\n //next word is in wordList\n //append this word to path\n //path will be reused in the loop\n //so copy a new path\n vector<string> newpath = path;\n newpath.push_back(news);\n visited.insert(news);\n if (news == endWord) {\n minLevel = level;\n ans.push_back(newpath);\n }\n else\n paths.push(newpath);\n }\n }\n }\n }\n return ans;\n }\n``` | 682 | 21 | [] | 99 |
word-ladder-ii | My concise JAVA solution based on BFS and DFS | my-concise-java-solution-based-on-bfs-an-xg53 | Explanation\n\nThe basic idea is:\n\n1). Use BFS to find the shortest distance between start and end, tracing the distance of crossing nodes from start node to | cheng_zhang | NORMAL | 2015-10-19T07:35:02+00:00 | 2018-10-25T08:52:41.694949+00:00 | 142,586 | false | **Explanation**\n\nThe basic idea is:\n\n1). Use BFS to find the shortest distance between start and end, tracing the distance of crossing nodes from start node to end node, and store node's next level neighbors to HashMap;\n\n2). Use DFS to output paths with the same distance as the shortest distance from distance HashMap: compare if the distance of the next level node equals the distance of the current node + 1. \n\n```\npublic List<List<String>> findLadders(String start, String end, List<String> wordList) {\n HashSet<String> dict = new HashSet<String>(wordList);\n List<List<String>> res = new ArrayList<List<String>>(); \n HashMap<String, ArrayList<String>> nodeNeighbors = new HashMap<String, ArrayList<String>>();// Neighbors for every node\n HashMap<String, Integer> distance = new HashMap<String, Integer>();// Distance of every node from the start node\n ArrayList<String> solution = new ArrayList<String>();\n\n dict.add(start); \n bfs(start, end, dict, nodeNeighbors, distance); \n dfs(start, end, dict, nodeNeighbors, distance, solution, res); \n return res;\n}\n\n// BFS: Trace every node's distance from the start node (level by level).\nprivate void bfs(String start, String end, Set<String> dict, HashMap<String, ArrayList<String>> nodeNeighbors, HashMap<String, Integer> distance) {\n for (String str : dict)\n nodeNeighbors.put(str, new ArrayList<String>());\n\n Queue<String> queue = new LinkedList<String>();\n queue.offer(start);\n distance.put(start, 0);\n\n while (!queue.isEmpty()) {\n int count = queue.size();\n boolean foundEnd = false;\n for (int i = 0; i < count; i++) {\n String cur = queue.poll();\n int curDistance = distance.get(cur); \n ArrayList<String> neighbors = getNeighbors(cur, dict);\n\n for (String neighbor : neighbors) {\n nodeNeighbors.get(cur).add(neighbor);\n if (!distance.containsKey(neighbor)) {// Check if visited\n distance.put(neighbor, curDistance + 1);\n if (end.equals(neighbor))// Found the shortest path\n foundEnd = true;\n else\n queue.offer(neighbor);\n }\n }\n }\n\n if (foundEnd)\n break;\n }\n }\n\n// Find all next level nodes. \nprivate ArrayList<String> getNeighbors(String node, Set<String> dict) {\n ArrayList<String> res = new ArrayList<String>();\n char chs[] = node.toCharArray();\n\n for (char ch ='a'; ch <= 'z'; ch++) {\n for (int i = 0; i < chs.length; i++) {\n if (chs[i] == ch) continue;\n char old_ch = chs[i];\n chs[i] = ch;\n if (dict.contains(String.valueOf(chs))) {\n res.add(String.valueOf(chs));\n }\n chs[i] = old_ch;\n }\n\n }\n return res;\n}\n\n// DFS: output all paths with the shortest distance.\nprivate void dfs(String cur, String end, Set<String> dict, HashMap<String, ArrayList<String>> nodeNeighbors, HashMap<String, Integer> distance, ArrayList<String> solution, List<List<String>> res) {\n solution.add(cur);\n if (end.equals(cur)) {\n res.add(new ArrayList<String>(solution));\n } else {\n for (String next : nodeNeighbors.get(cur)) { \n if (distance.get(next) == distance.get(cur) + 1) {\n dfs(next, end, dict, nodeNeighbors, distance, solution, res);\n }\n }\n } \n solution.remove(solution.size() - 1);\n}\n``` | 472 | 8 | [] | 81 |
word-ladder-ii | Python simple BFS layer by layer | python-simple-bfs-layer-by-layer-by-abye-vy1t | \nclass Solution(object):\n def findLadders(self, beginWord, endWord, wordList):\n\n wordList = set(wordList)\n res = []\n layer = {}\n | abyellow7511 | NORMAL | 2017-05-21T12:44:21.050000+00:00 | 2018-10-24T02:05:58.645412+00:00 | 39,929 | false | ```\nclass Solution(object):\n def findLadders(self, beginWord, endWord, wordList):\n\n wordList = set(wordList)\n res = []\n layer = {}\n layer[beginWord] = [[beginWord]]\n\n while layer:\n newlayer = collections.defaultdict(list)\n for w in layer:\n if w == endWord: \n res.extend(k for k in layer[w])\n else:\n for i in range(len(w)):\n for c in 'abcdefghijklmnopqrstuvwxyz':\n neww = w[:i]+c+w[i+1:]\n if neww in wordList:\n newlayer[neww]+=[j+[neww] for j in layer[w]]\n\n wordList -= set(newlayer.keys())\n layer = newlayer\n\n return res\n``` | 270 | 12 | [] | 53 |
word-ladder-ii | Python BFS+Backtrack Greatly Improved by bi-directional BFS | python-bfsbacktrack-greatly-improved-by-9x6ps | An intuitive solution is to use BFS to find shorterst transformation path from begin word to end word. A valid transformation is to change any one character and | wangqiuc | NORMAL | 2019-04-05T05:24:57.456344+00:00 | 2021-10-04T01:22:15.483653+00:00 | 21,708 | false | An intuitive solution is to use BFS to find shorterst transformation path from begin word to end word. A valid transformation is to change any one character and transformed word should be in the a word list.\n\nWhat is tricker than #127 is that we need to find all shortest paths. Thus, we need to build a search tree during BFS and backtrack along that tree to restore all shortest paths. \nSo we can\'t stop BFS once we found a transformed word is endword but instead finishing searching is this BFS layer since there could be more than one shortest path.\nAnd we still need to rule out all node that we have searched previously. Meanwhile if two nodes have a same child node, we need to add that child node to both node\'s children list as we need to backtrack all valid paths. So unlike a regular BFS, we can\'t use a "seen" set but a more like "explored" set. Otherwise, e.g. tree: {x->z, y->z}, z won\'t be added to y\'s children list if x is visited first and z is already seen in x\'s search.\n```\ndef findLadders(beginWord, endWord, wordList):\n\ttree, words, n = collections.defaultdict(set), set(wordList), len(beginWord)\n\tif endWord not in wordList: return []\n\tfound, q, nq = False, {beginWord}, set()\n\twhile q and not found:\n\t\twords -= set(q)\n\t\tfor x in q:\n\t\t\tfor y in [x[:i]+c+x[i+1:] for i in range(n) for c in string.ascii_lowercase]:\n\t\t\t\tif y in words:\n\t\t\t\t\tif y == endWord: \n\t\t\t\t\t\tfound = True\n\t\t\t\t\telse: \n\t\t\t\t\t\tnq.add(y)\n\t\t\t\t\ttree[x].add(y)\n\t\tq, nq = nq, set()\n\tdef bt(x): \n\t\treturn [[x]] if x == endWord else [[x] + rest for y in tree[x] for rest in bt(y)]\n\treturn bt(beginWord)\n```\nThat\'s single one-way BFS which cost more than 2500ms. BFS\'t time complexity is O(b^d) where b is branch factor and d is depth. So if we go with a bi-directional way, expanding from both being word and end word, and choosing the queue (\'begin\' queue or \'end\' queue) with smaller size in each expansion, the branch factor will be greatly reduced.\nAnd bi-directional BFS reducing running time from 2500ms to 100ms!\n```\ndef findLadders(beginWord, endWord, wordList):\n\ttree, words, n = collections.defaultdict(set), set(wordList), len(beginWord)\n\tif endWord not in wordList: return []\n\tfound, bq, eq, nq, rev = False, {beginWord}, {endWord}, set(), False\n\twhile bq and not found:\n\t\twords -= set(bq)\n\t\tfor x in bq:\n\t\t\tfor y in [x[:i]+c+x[i+1:] for i in range(n) for c in string.ascii_lowercase]:\n\t\t\t\tif y in words:\n\t\t\t\t\tif y in eq: \n\t\t\t\t\t\tfound = True\n\t\t\t\t\telse: \n\t\t\t\t\t\tnq.add(y)\n\t\t\t\t\ttree[y].add(x) if rev else tree[x].add(y)\n\t\tbq, nq = nq, set()\n\t\tif len(bq) > len(eq): \n\t\t\tbq, eq, rev = eq, bq, not rev\n\tdef bt(x): \n\t\treturn [[x]] if x == endWord else [[x] + rest for y in tree[x] for rest in bt(y)]\n\treturn bt(beginWord)\n``` | 224 | 6 | ['Python'] | 34 |
word-ladder-ii | [C++/Python] BFS Level by Level - with Picture - Clean & Concise | cpython-bfs-level-by-level-with-picture-zgawy | Idea\n- This problem is an advanced version of 127. Word Ladder, I highly recommend solving it first if you haven\'t solved it yet.\n- To find the shortest path | hiepit | NORMAL | 2021-07-24T09:31:23.054801+00:00 | 2021-07-25T04:42:31.448249+00:00 | 19,860 | false | **Idea**\n- This problem is an advanced version of **[127. Word Ladder](https://leetcode.com/problems/word-ladder/)**, I highly recommend solving it first if you haven\'t solved it yet.\n- To find the shortest path from `beginWord` to `endWord`, we need to use BFS.\n- To find neighbors of a `word`, we just try to change each position from the original `word`, each position we try to change letters from `a..z`, the neighbors are valid if and only if they\'re existed in the `wordList`.\n- The problem is required to output the answer sequence paths, so we need to store sequences path so far while doing bfs.\n\t- Let `level[word]` is the all possible sequence paths which start from `beginWord` and end at `word`. \n\t- Then `level[endWord]` is our answer.\n\n\n\n\n<iframe src="https://leetcode.com/playground/6pRoqS4A/shared" frameBorder="0" width="100%" height="720"></iframe>\n\n**Complexity**\n- Time: `O(N * 26 * W^2 + A)`, where `N <= 1000` is number of words in `wordList`, `W <= 5` is length of each words, `A` is total number of sequences.\n\t- BFS costs `O(E + V)`, where `E` is number of edges, `V` is number of vertices.\n\t- Because words need to be existed in the `wordList`, so there is total `N` words, it\'s also the number of vertices.\n\t- To find neighbors for a `word`, it costs `O(26 * W * W)`, in the worst case, we have to find the neighbors of `N` words, so there is total `O(N * 26 * W^2)` edges.\n- Space: `O(N*W + A)`\n\n\nIf you think this **post is useful**, I\'m happy if you **give a vote**. Any **questions or discussions are welcome!** Thank a lot. | 195 | 15 | [] | 17 |
word-ladder-ii | [C++] ✅ using BFS and Backtracking || 🔥 NO TLE | c-using-bfs-and-backtracking-no-tle-by-h-xrao | This solution relies on first finding the shortest transformation length between the beginWord and endWord strings and then performing a recursive backtrack to | hoshang2900 | NORMAL | 2022-08-14T00:14:31.561790+00:00 | 2023-03-12T09:41:25.769364+00:00 | 30,695 | false | This solution relies on first finding the shortest transformation length between the beginWord and endWord strings and then performing a recursive backtrack to find all possible paths of the same length.\n\nWe start by checking if endWord is in the wordList; if it isn\'t, we cannot have a path from beginWord to endWord. Then, we perform a breadth-first search on our "graph" of words. The vertices in this graph are defined by words in our wordList, while edges between two vertices exist if we canTransform the words into each other (i.e. change one of the letters to arrive at a new word). While performing this search, we keep track of the parents of each word (this will allow us to recursively construct all valid paths later on). In this problem, since we are keeping track of a directed series of transformations, if we transform string a into string b, we say that a is a parent of b, and we track this in our parents map, which stores all the parents we encounter for a particular word. Note that we only care about relevant parents on the shortest path to a word, since we are trying to find the shortest path from source to destination, and once we have encountered a word, if we encounter it again on a longer path this new path cannot be the shortest path from beginWord to endWord.\n\nNow, once we find the endWord, we keep track of the shortestpath length in variable. Note that once we find this, since we are keeping track of a word\'s parent at the time the word is queued in traverse, all possible parents that have a shortest path length for endWord must already be accounted for.\n\nFinally, we recursively trace back through each node\'s parents (starting at endWord) and construct all valid paths. At each function call, we go through all possible parents for a given word, and if we arrive at the beginWord in the correct amount of steps, we add the path to our answer. Since we construct these paths in reverse order, we must invert them all at the end.\n\n\t// BFS gives TLE if we store path while traversing because whenever we find a better visit time for a word, we have to clear/make a new path vector everytime. \n\t// The idea is to first use BFS to search from beginWord to endWord and generate the word-to-children mapping at the same time. \n\t// Then, use DFS (backtracking) to generate the transformation sequences according to the mapping. \n\t// The reverse DFS allows us to only make the shortest paths, never having to clear a whole sequence when we encounter better result in BFS\n\t// No string operations are done, by dealing with indices instead.\n\n\n\n\tclass Solution {\n\tpublic:\n bool able(string s,string t){\n int c=0;\n for(int i=0;i<s.length();i++)\n c+=(s[i]!=t[i]);\n return c==1;\n }\n void bfs(vector<vector<int>> &g,vector<int> parent[],int n,int start,int end){\n vector <int> dist(n,1005);\n queue <int> q;\n q.push(start);\n parent[start]={-1};\n dist[start]=0;\n while(!q.empty()){\n int x=q.front();\n q.pop();\n for(int u:g[x]){\n if(dist[u]>dist[x]+1){\n dist[u]=dist[x]+1;\n q.push(u);\n parent[u].clear();\n parent[u].push_back(x);\n }\n else if(dist[u]==dist[x]+1)\n parent[u].push_back(x);\n }\n }\n }\n void shortestPaths(vector<vector<int>> &Paths, vector<int> &path, vector<int> parent[],int node){\n if(node==-1){\n // as parent of start was -1, we\'ve completed the backtrack\n Paths.push_back(path);\n return ;\n }\n for(auto u:parent[node]){\n path.push_back(u);\n shortestPaths(Paths,path,parent,u);\n path.pop_back();\n }\n }\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n // start and end are indices of beginWord and endWord\n int n=wordList.size(),start=-1,end=-1;\n vector<vector<string>> ANS;\n for(int i=0;i<n;i++){\n if(wordList[i]==beginWord)\n start=i;\n if(wordList[i]==endWord)\n end=i;\n }\n \n // if endWord doesn\'t exist, return empty list\n if(end==-1)\n return ANS;\n \n // if beginWord doesn\'t exist, add it in start of WordList\n if(start==-1){\n wordList.emplace(wordList.begin(),beginWord);\n start=0;\n end++;\n n++;\n }\n // for each word, we\'re making adjency list of neighbour words (words that can be made with one letter change)\n // Paths will store all the shortest paths (formed later by backtracking)\n vector<vector<int>> g(n,vector<int>()),Paths;\n \n // storing possible parents for each word (to backtrack later), path is the current sequence (while backtracking)\n vector<int> parent[n],path;\n \n // creating adjency list for each pair of words in the wordList (including beginword)\n for(int i=0;i<n-1;i++)\n for(int j=i+1;j<n;j++)\n if(able(wordList[i],wordList[j])){\n g[i].push_back(j);\n g[j].push_back(i);\n }\n \n bfs(g,parent,n,start,end); \n \n // backtracking to make shortestpaths\n shortestPaths(Paths,path,parent,end);\n for(auto u:Paths){\n vector <string> now;\n for(int i=0;i<u.size()-1;i++)\n now.push_back(wordList[u[i]]);\n reverse(now.begin(),now.end());\n now.push_back(wordList[end]);\n ANS.push_back(now);\n }\n return ANS;\n }\n\t}; \n\t\n**Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community).**\n\n**HAPPY CODING:)**\n\n*Any suggestions and improvements are always welcome*\n\t\n\t\n\t | 168 | 2 | ['Backtracking', 'Depth-First Search', 'Breadth-First Search', 'C', 'C++'] | 15 |
word-ladder-ii | Share two similar Java solution that Accpted by OJ. | share-two-similar-java-solution-that-acc-jbu8 | The solution contains two steps 1 Use BFS to construct a graph. 2. Use DFS to construct the paths from end to start.Both solutions got AC within 1s. \n\nThe fir | reeclapple | NORMAL | 2014-08-20T18:06:32+00:00 | 2018-10-25T14:49:36.065842+00:00 | 86,675 | false | The solution contains two steps 1 Use BFS to construct a graph. 2. Use DFS to construct the paths from end to start.Both solutions got AC within 1s. \n\nThe first step BFS is quite important. I summarized three tricks\n\n1) Using a **MAP** to store the min ladder of each word, or use a **SET** to store the words visited in current ladder, when the current ladder was completed, delete the visited words from unvisited. That's why I have two similar solutions. \n\n\n2) Use **Character iteration** to find all possible paths. Do not compare one word to all the other words and check if they only differ by one character.\n\n\n3) One word is allowed to be inserted into the queue only **ONCE**. See my comments.\n\n\n public class Solution {\n \tMap<String,List<String>> map;\n \tList<List<String>> results;\n public List<List<String>> findLadders(String start, String end, Set<String> dict) { \t\n results= new ArrayList<List<String>>();\n if (dict.size() == 0)\n \t\t\treturn results;\n \n int min=Integer.MAX_VALUE;\n \n Queue<String> queue= new ArrayDeque<String>();\n queue.add(start);\n \n \t\tmap = new HashMap<String,List<String>>();\n \t\t\n \t\tMap<String,Integer> ladder = new HashMap<String,Integer>();\n \t\tfor (String string:dict)\n \t\t ladder.put(string, Integer.MAX_VALUE);\n \t\tladder.put(start, 0);\n \t\t\t\t\n \t\tdict.add(end);\n \t\t//BFS: Dijisktra search\n \t\twhile (!queue.isEmpty()) {\n \t\t \n \t\t\tString word = queue.poll();\n \t\t\t\n \t\t\tint step = ladder.get(word)+1;//'step' indicates how many steps are needed to travel to one word. \n \t\t\t\n \t\t\tif (step>min) break;\n \t\t\t\n \t\t\tfor (int i = 0; i < word.length(); i++){\n \t\t\t StringBuilder builder = new StringBuilder(word); \n \t\t\t\tfor (char ch='a'; ch <= 'z'; ch++){\n \t\t\t\t\tbuilder.setCharAt(i,ch);\n \t\t\t\t\tString new_word=builder.toString();\t\t\t\t\n \t\t\t\t\tif (ladder.containsKey(new_word)) {\n \t\t\t\t\t\t\t\n \t\t\t\t\t if (step>ladder.get(new_word))//Check if it is the shortest path to one word.\n \t\t\t\t\t \tcontinue;\n \t\t\t\t\t else if (step<ladder.get(new_word)){\n \t\t\t\t\t \tqueue.add(new_word);\n \t\t\t\t\t \tladder.put(new_word, step);\n \t\t\t\t\t }else;// It is a KEY line. If one word already appeared in one ladder,\n \t\t\t\t\t // Do not insert the same word inside the queue twice. Otherwise it gets TLE.\n \t\t\t\t\t \n \t\t\t\t\t if (map.containsKey(new_word)) //Build adjacent Graph\n \t\t\t\t\t \tmap.get(new_word).add(word);\n \t\t\t\t\t else{\n \t\t\t\t\t \tList<String> list= new LinkedList<String>();\n \t\t\t\t\t \tlist.add(word);\n \t\t\t\t\t \tmap.put(new_word,list);\n \t\t\t\t\t \t//It is possible to write three lines in one:\n \t\t\t\t\t \t//map.put(new_word,new LinkedList<String>(Arrays.asList(new String[]{word})));\n \t\t\t\t\t \t//Which one is better?\n \t\t\t\t\t }\n \t\t\t\t\t \n \t\t\t\t\t if (new_word.equals(end))\n \t\t\t\t\t \tmin=step;\n \n \t\t\t\t\t}//End if dict contains new_word\n \t\t\t\t}//End:Iteration from 'a' to 'z'\n \t\t\t}//End:Iteration from the first to the last\n \t\t}//End While\n \n \t//BackTracking\n \t\tLinkedList<String> result = new LinkedList<String>();\n \t\tbackTrace(end,start,result);\n \n \t\treturn results; \n }\n private void backTrace(String word,String start,List<String> list){\n \tif (word.equals(start)){\n \t\tlist.add(0,start);\n \t\tresults.add(new ArrayList<String>(list));\n \t\tlist.remove(0);\n \t\treturn;\n \t}\n \tlist.add(0,word);\n \tif (map.get(word)!=null)\n \t\tfor (String s:map.get(word))\n \t\t\tbackTrace(s,start,list);\n \tlist.remove(0);\n }\n }\n\n\nAnother solution using two sets. This is similar to the answer in the most viewed thread. While I found my solution more readable and efficient. \n\n public class Solution {\n \tList<List<String>> results;\n \tList<String> list;\n \tMap<String,List<String>> map;\n \t public List<List<String>> findLadders(String start, String end, Set<String> dict) {\n \t results= new ArrayList<List<String>>();\n \t if (dict.size() == 0)\n \t\t\t\treturn results;\n \t \n \t int curr=1,next=0;\t \n \t boolean found=false;\t \n \t list = new LinkedList<String>();\t \n \t\t\tmap = new HashMap<String,List<String>>();\n \t\t\t\n \t\t\tQueue<String> queue= new ArrayDeque<String>();\n \t\t\tSet<String> unvisited = new HashSet<String>(dict);\n \t\t\tSet<String> visited = new HashSet<String>();\n \t\t\t\n \t\t\tqueue.add(start);\t\t\t\n \t\t\tunvisited.add(end);\n \t\t\tunvisited.remove(start);\n \t\t\t//BFS\n \t\t\twhile (!queue.isEmpty()) {\n \t\t\t \n \t\t\t\tString word = queue.poll();\n \t\t\t\tcurr--;\t\t\t\t\n \t\t\t\tfor (int i = 0; i < word.length(); i++){\n \t\t\t\t StringBuilder builder = new StringBuilder(word); \n \t\t\t\t\tfor (char ch='a'; ch <= 'z'; ch++){\n \t\t\t\t\t\tbuilder.setCharAt(i,ch);\n \t\t\t\t\t\tString new_word=builder.toString();\t\n \t\t\t\t\t\tif (unvisited.contains(new_word)){\n \t\t\t\t\t\t\t//Handle queue\n \t\t\t\t\t\t\tif (visited.add(new_word)){//Key statement,Avoid Duplicate queue insertion\n \t\t\t\t\t\t\t\tnext++;\n \t\t\t\t\t\t\t\tqueue.add(new_word);\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t\n \t\t\t\t\t\t\tif (map.containsKey(new_word))//Build Adjacent Graph\n \t\t\t\t\t\t\t\tmap.get(new_word).add(word);\n \t\t\t\t\t\t\telse{\n \t\t\t\t\t\t\t\tList<String> l= new LinkedList<String>();\n \t\t\t\t\t\t\t\tl.add(word);\n \t\t\t\t\t\t\t\tmap.put(new_word, l);\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t\n \t\t\t\t\t\t\tif (new_word.equals(end)&&!found) found=true;\t\t\n \t\t\t\t\t\t\t\t\t\t\t\t\t\t\n \t\t\t\t\t\t}\n \n \t\t\t\t\t}//End:Iteration from 'a' to 'z'\n \t\t\t\t}//End:Iteration from the first to the last\n \t\t\t\tif (curr==0){\n \t\t\t\t\tif (found) break;\n \t\t\t\t\tcurr=next;\n \t\t\t\t\tnext=0;\n \t\t\t\t\tunvisited.removeAll(visited);\n \t\t\t\t\tvisited.clear();\n \t\t\t\t}\n \t\t\t}//End While\n \n \t\t\tbackTrace(end,start);\n \t\t\t\n \t\t\treturn results; \n \t }\n \t private void backTrace(String word,String start){\n \t \tif (word.equals(start)){\n \t \t\tlist.add(0,start);\n \t \t\tresults.add(new ArrayList<String>(list));\n \t \t\tlist.remove(0);\n \t \t\treturn;\n \t \t}\n \t \tlist.add(0,word);\n \t \tif (map.get(word)!=null)\n \t \t\tfor (String s:map.get(word))\n \t \t\t\tbackTrace(s,start);\n \t \tlist.remove(0);\n \t }\n \t} | 142 | 7 | ['Depth-First Search', 'Breadth-First Search', 'Java'] | 37 |
word-ladder-ii | Three Python solutions: Only BFS, BFS+DFS, biBFS+ DFS | three-python-solutions-only-bfs-bfsdfs-b-4g0l | Solution 1, BFS, directly store the path in queue. 318 ms, 18.7 MB\nSolution 2, BFS to build graph (parents), DFS to get the shortest path, 356 ms, 20.6 MB\nS | zyzflying | NORMAL | 2020-01-26T00:02:56.077396+00:00 | 2020-07-01T19:05:09.155726+00:00 | 12,946 | false | Solution 1, BFS, directly store the path in queue. 318 ms, 18.7 MB\nSolution 2, BFS to build graph (parents), DFS to get the shortest path, 356 ms, 20.6 MB\nSolution 3, biBFS to build graph (parents), DFS to get the shortest path, 224 ms, 18.9 MB\nNote that: propocessing words as below will greatly improve the algorithm speed. \n``` python\n# Dictionary to hold combination of words that can be formed,\n# from any given word. By changing one letter at a time.\nall_combo_dict = collections.defaultdict(list)\nfor word in wordList:\n\tfor i in range(L):\n\t\tall_combo_dict[word[:i] + "*" + word[i+1:]].append(word)\n```\n\n``` python \n## Solution 1\ndef findLadders(self, beginWord, endWord, wordList):\n\tif not endWord or not beginWord or not wordList or endWord not in wordList \\\n\t\tor beginWord == endWord:\n\t\treturn []\n\n\tL = len(beginWord)\n\n\t# Dictionary to hold combination of words that can be formed,\n\t# from any given word. By changing one letter at a time.\n\tall_combo_dict = collections.defaultdict(list)\n\tfor word in wordList:\n\t\tfor i in range(L):\n\t\t\tall_combo_dict[word[:i] + "*" + word[i+1:]].append(word)\n\n\t# Shortest path, BFS\n\tans = []\n\tqueue = collections.deque()\n\tqueue.append((beginWord, [beginWord]))\n\tvisited = set([beginWord])\n\t\n\twhile queue and not ans:\n\t\t# print(queue)\n\t\tlength = len(queue)\n\t\t# print(queue)\n\t\tlocalVisited = set()\n\t\tfor _ in range(length):\n\t\t\tword, path = queue.popleft()\n\t\t\tfor i in range(L):\n\t\t\t\tfor nextWord in all_combo_dict[word[:i] + "*" + word[i+1:]]:\n\t\t\t\t\tif nextWord == endWord:\n\t\t\t\t\t\t# path.append(endword)\n\t\t\t\t\t\tans.append(path+[endWord])\n\t\t\t\t\tif nextWord not in visited:\n\t\t\t\t\t\tlocalVisited.add(nextWord)\n\t\t\t\t\t\tqueue.append((nextWord, path+[nextWord]))\n\t\tvisited = visited.union(localVisited)\n\treturn ans\n```\n\n```python \n## Solution 2\ndef findLadders(self, beginWord, endWord, wordList):\n\t"""\n\t:type beginWord: str\n\t:type endWord: str\n\t:type wordList: List[str]\n\t:rtype: List[List[str]]\n\t"""\n\tif not endWord or not beginWord or not wordList or endWord not in wordList \\\n\t\tor beginWord == endWord:\n\t\treturn []\n\n\tL = len(beginWord)\n\n\t# Dictionary to hold combination of words that can be formed,\n\t# from any given word. By changing one letter at a time.\n\tall_combo_dict = collections.defaultdict(list)\n\tfor word in wordList:\n\t\tfor i in range(L):\n\t\t\tall_combo_dict[word[:i] + "*" + word[i+1:]].append(word)\n\n\t# Build graph, BFS\n\t# ans = []\n\tqueue = collections.deque()\n\tqueue.append(beginWord)\n\tparents = collections.defaultdict(set)\n\tvisited = set([beginWord])\n\tfound = False \n\tdepth = 0\n\twhile queue and not found:\n\t\tdepth += 1 \n\t\tlength = len(queue)\n\t\t# print(queue)\n\t\tlocalVisited = set()\n\t\tfor _ in range(length):\n\t\t\tword = queue.popleft()\n\t\t\tfor i in range(L):\n\t\t\t\tfor nextWord in all_combo_dict[word[:i] + "*" + word[i+1:]]:\n\t\t\t\t\tif nextWord == word:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif nextWord not in visited:\n\t\t\t\t\t\tparents[nextWord].add(word)\n\t\t\t\t\t\tif nextWord == endWord: \n\t\t\t\t\t\t\tfound = True\n\t\t\t\t\t\tlocalVisited.add(nextWord)\n\t\t\t\t\t\tqueue.append(nextWord)\n\t\tvisited = visited.union(localVisited)\n\t# print(parents)\n\t# Search path, DFS\n\tans = []\n\tdef dfs(node, path, d):\n\t\tif d == 0:\n\t\t\tif path[-1] == beginWord:\n\t\t\t\tans.append(path[::-1])\n\t\t\treturn \n\t\tfor parent in parents[node]:\n\t\t\tpath.append(parent)\n\t\t\tdfs(parent, path, d-1)\n\t\t\tpath.pop()\n\tdfs(endWord, [endWord], depth)\n\treturn ans\n```\n\n``` python\n## Solution 3\ndef findLadders(self, beginWord, endWord, wordList):\n\t"""\n\t:type beginWord: str\n\t:type endWord: str\n\t:type wordList: List[str]\n\t:rtype: List[List[str]]\n\t"""\n\tif not endWord or not beginWord or not wordList or endWord not in wordList \\\n\t\tor beginWord == endWord:\n\t\treturn []\n\n\tL = len(beginWord)\n\n\t# Dictionary to hold combination of words that can be formed,\n\t# from any given word. By changing one letter at a time.\n\tall_combo_dict = collections.defaultdict(list)\n\tfor word in wordList:\n\t\tfor i in range(L):\n\t\t\tall_combo_dict[word[:i] + "*" + word[i+1:]].append(word)\n\n\t# Build graph, bi-BFS\n\t# ans = []\n\tbqueue = collections.deque()\n\tbqueue.append(beginWord)\n\tequeue = collections.deque()\n\tequeue.append(endWord)\n\tbvisited = set([beginWord])\n\tevisited = set([endWord])\n\trev = False \n\t#graph\n\tparents = collections.defaultdict(set)\n\tfound = False \n\tdepth = 0\n\twhile bqueue and not found:\n\t\tdepth += 1 \n\t\tlength = len(bqueue)\n\t\t# print(queue)\n\t\tlocalVisited = set()\n\t\tfor _ in range(length):\n\t\t\tword = bqueue.popleft()\n\t\t\tfor i in range(L):\n\t\t\t\tfor nextWord in all_combo_dict[word[:i] + "*" + word[i+1:]]:\n\t\t\t\t\tif nextWord == word:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif nextWord not in bvisited:\n\t\t\t\t\t\tif not rev:\n\t\t\t\t\t\t\tparents[nextWord].add(word)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tparents[word].add(nextWord)\n\t\t\t\t\t\tif nextWord in evisited: \n\t\t\t\t\t\t\tfound = True\n\t\t\t\t\t\tlocalVisited.add(nextWord)\n\t\t\t\t\t\tbqueue.append(nextWord)\n\t\tbvisited = bvisited.union(localVisited)\n\t\tbqueue, bvisited, equeue, evisited, rev = equeue, evisited, bqueue, bvisited, not rev\n\t# print(parents)\n\t# print(depth)\n\t# Search path, DFS\n\tans = []\n\tdef dfs(node, path, d):\n\t\tif d == 0:\n\t\t\tif path[-1] == beginWord:\n\t\t\t\tans.append(path[::-1])\n\t\t\treturn \n\t\tfor parent in parents[node]:\n\t\t\tpath.append(parent)\n\t\t\tdfs(parent, path, d-1)\n\t\t\tpath.pop()\n\tdfs(endWord, [endWord], depth)\n\treturn ans\n``` | 119 | 0 | ['Breadth-First Search', 'Python'] | 13 |
word-ladder-ii | Super fast Java solution (two-end BFS) | super-fast-java-solution-two-end-bfs-by-6p645 | Thanks to prime_tang and jianchao.li.fighter!\n\n public List> findLadders(String start, String end, Set dict) {\n // hash set for both ends\n | jeantimex | NORMAL | 2015-07-06T22:47:06+00:00 | 2018-09-18T23:17:28.882068+00:00 | 49,063 | false | Thanks to prime_tang and jianchao.li.fighter!\n\n public List<List<String>> findLadders(String start, String end, Set<String> dict) {\n // hash set for both ends\n Set<String> set1 = new HashSet<String>();\n Set<String> set2 = new HashSet<String>();\n \n // initial words in both ends\n set1.add(start);\n set2.add(end);\n \n // we use a map to help construct the final result\n Map<String, List<String>> map = new HashMap<String, List<String>>();\n \n // build the map\n helper(dict, set1, set2, map, false);\n \n List<List<String>> res = new ArrayList<List<String>>();\n List<String> sol = new ArrayList<String>(Arrays.asList(start));\n \n // recursively build the final result\n generateList(start, end, map, sol, res);\n \n return res;\n }\n \n boolean helper(Set<String> dict, Set<String> set1, Set<String> set2, Map<String, List<String>> map, boolean flip) {\n if (set1.isEmpty()) {\n return false;\n }\n \n if (set1.size() > set2.size()) {\n return helper(dict, set2, set1, map, !flip);\n }\n \n // remove words on current both ends from the dict\n dict.removeAll(set1);\n dict.removeAll(set2);\n \n // as we only need the shortest paths\n // we use a boolean value help early termination\n boolean done = false;\n \n // set for the next level\n Set<String> set = new HashSet<String>();\n \n // for each string in end 1\n for (String str : set1) {\n for (int i = 0; i < str.length(); i++) {\n char[] chars = str.toCharArray();\n \n // change one character for every position\n for (char ch = 'a'; ch <= 'z'; ch++) {\n chars[i] = ch;\n \n String word = new String(chars);\n \n // make sure we construct the tree in the correct direction\n String key = flip ? word : str;\n String val = flip ? str : word;\n \n List<String> list = map.containsKey(key) ? map.get(key) : new ArrayList<String>();\n \n if (set2.contains(word)) {\n done = true;\n \n list.add(val);\n map.put(key, list);\n } \n \n if (!done && dict.contains(word)) {\n set.add(word);\n \n list.add(val);\n map.put(key, list);\n }\n }\n }\n }\n \n // early terminate if done is true\n return done || helper(dict, set2, set, map, !flip);\n }\n \n void generateList(String start, String end, Map<String, List<String>> map, List<String> sol, List<List<String>> res) {\n if (start.equals(end)) {\n res.add(new ArrayList<String>(sol));\n return;\n }\n \n // need this check in case the diff between start and end happens to be one\n // e.g "a", "c", {"a", "b", "c"}\n if (!map.containsKey(start)) {\n return;\n }\n \n for (String word : map.get(start)) {\n sol.add(word);\n generateList(word, end, map, sol, res);\n sol.remove(sol.size() - 1);\n }\n } | 101 | 4 | ['Breadth-First Search', 'Java'] | 16 |
word-ladder-ii | ✅ Word Ladder II [No TLE] || With Approach || Using BFS | word-ladder-ii-no-tle-with-approach-usin-nzpt | Due to new testcases, the old solutions are giving TLE\n\n# APPROACH:\nGiven two words (beginWord and endWord), and a dictionary\u2019s word list, find all shor | Maango16 | NORMAL | 2021-07-24T07:13:57.391576+00:00 | 2022-08-14T05:59:40.284985+00:00 | 12,337 | false | *Due to new testcases, the old solutions are giving TLE*\n\n# **APPROACH:**\nGiven two words (beginWord and endWord), and a dictionary\u2019s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:\n1. Only one letter can be changed at a time\n1. Each transformed word must exist in the word list. Note that beginWordis not a transformed word.\n\n**MUST DO:** This question is an advanced version of 127. Word Ladder. So try that too. [Question Link](https://leetcode.com/problems/word-ladder/)\n\n**EXAMPLE:** \nHere is an example of Word Ladder\n\n\n\n\n**KEEP IN MIND:**\n* Return an empty list if there is no such transformation sequence.\n* All words have the same length.\n* All words contain only lowercase alphabetic characters.\n* You may assume no duplicates in the word list.\n* You may assume beginWord and endWord are non-empty and are not the same.\n\n\u274C ***Solution - I (TLE)***\n\n<details>\n<summary> Solution </summary>\n\n```\nclass Solution {\npublic:\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n unordered_map<string,int> mp ; \n // Record the number of conversions required to reach this string\n vector<vector<string>> ans ;\n\t\t//add words to map\n for(const auto w:wordList) \n {\n mp.insert({w,INT_MAX});\n }\n mp[beginWord]=0; \n\n\t\t//queue which stores word along sequence till now\n queue<pair<string,vector<string>>> q;\n q.push({beginWord,{beginWord}});\n\t\t\n while(!q.empty())\n {\n auto n = q.front() ;\n q.pop() ;\n\t\t\t//find word and sequence\n string w = n.first ;\n auto v=n.second ;\n\t\t\t\n\t\t\t//found one solution, add to result set and continue\n if(w==endWord)\n {\n ans.push_back(v);\n continue;\n }\n\t\t\t//explore possibilities from this word \n\t\t\t\n for(int i = 0 ; i < w.size() ; i++)\n {\n string t = w ;\n for(char c=\'a\' ; c <= \'z\' ; c++)\n {\n t[i] = c ;\n if(t==w)\n {\n continue ;\n }\n if(mp.find(t)==mp.end())\n {\n continue ;\n }\n if(mp[t]<(int)v.size())\n {\n continue ;\n } \n mp[t] = (int)v.size() ;\n v.push_back(t) ;\n q.push({t,v}) ;\n v.pop_back() ;\n }\n }\n }\n return ans ;\n }\n};\n```\n</details>\n\n<hr>\n\n\u2714\uFE0F ***Solution - II***\n```\nclass Solution {\npublic:\n bool neighbour(string a, string b){\n int cnt = 0 ;\n for(int i = 0 ; i < a.length() ; i++)\n {\n if(a[i] != b[i])\n {\n cnt++ ;\n }\n }\n return cnt == 1 ;\n }\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n wordList.insert(wordList.begin(), beginWord);\n for(int i = 1 ; i < wordList.size() ; i++)\n {\n if(wordList[i] == wordList[0]) // string compare\n {\n wordList[i] = wordList.back() ;\n wordList.pop_back() ;\n break ;\n }\n }\n map<string, int> wti ; // word to index\n for(int i = 0 ; i < wordList.size() ; i++)\n {\n wti.insert({wordList[i], i}) ;\n }\n if(!wti.count(endWord)) \n {\n return {} ;\n }\n vector<vector<int>> edges(wti.size()) ;\n for(int i = 0 ; i < wordList.size() ; i++)\n {\n for(int j = 0 ; j < wordList.size() ; j++)\n {\n if(i != j)\n {\n if(neighbour(wordList[i], wordList[j]))\n {\n edges[i].push_back(j) ;\n }\n }\n }\n }\n // BFS \n int start_node = 0 , target_node = wti[endWord] , r = 0 , min_step = INT_MAX ;\n vector<int> vis(wordList.size(), INT_MAX) ; \n vis[start_node] = 0 ;\n queue<int> q ; \n q.push(start_node) ;\n while(!q.empty())\n {\n int sz = q.size() ;\n for (int i = 0 ; i < sz ; i++)\n {\n int fr = q.front() ; \n q.pop() ;\n if(fr == target_node)\n {\n min_step = min(min_step , r) ;\n }\n for(int j = 0 ; j < edges[fr].size() ; j++)\n {\n int update_node = edges[fr][j] ;\n if(r + 1 < vis[update_node])\n {\n vis[update_node] = r + 1 ;\n q.push(update_node);\n }\n }\n }\n r++ ;\n }\n if(min_step == INT_MAX)\n {\n return {} ;\n }\n queue<vector<string>> q2 ; \n q2.push({wordList[target_node]}) ;\n r = min_step ;\n while(r)\n {\n int sz = q2.size() ;\n for(int i = 0 ; i < sz ; i++)\n {\n vector<string> seq = q2.front() ;\n q2.pop();\n string back = seq.back() ;\n int curr = wti[back] ;\n for (int j = 0 ; j < edges[curr].size() ; j++)\n {\n int new_node = edges[curr][j] ;\n if (vis[new_node] == r - 1)\n {\n seq.push_back(wordList[new_node]) ;\n q2.push(seq) ;\n seq.pop_back() ;\n }\n }\n }\n r-- ;\n }\n vector<vector<string>> ans;\n while(!q2.empty())\n {\n vector<string> temp = q2.front() ;\n q2.pop() ;\n reverse(begin(temp) , end(temp)) ;\n ans.push_back(temp) ;\n }\n return ans ;\n }\n};\n``` | 99 | 3 | ['C'] | 19 |
word-ladder-ii | Python BFS + DFS With Explanation Why Optimization Is Needed to Not TLE | python-bfs-dfs-with-explanation-why-opti-htyl | Intuition\n\n1. Most approaches start off with an adjacency list with a pattern node for quick lookups.\n\n1. Then we perform BFS until we reach an endWord. Sin | CompileTimeError | NORMAL | 2022-08-02T04:55:36.592640+00:00 | 2022-08-02T05:08:55.476251+00:00 | 6,112 | false | **Intuition**\n\n1. Most approaches start off with an adjacency list with a pattern node for quick lookups.\n\n1. Then we perform **BFS** until we reach an `endWord`. Since the question requires us to return all possible paths, it is very tempting to start constructing the path during our BFS\n\ta. **However**, this will always give us TLE. Algorithmically, this feels wrong since we need to explore and hit all the nodes at least once to form our path (i.e. `O(n)`).\n\tb. But looking at it more closely, we are creating/destroying paths at every node of a BFS traversal. Space and compute are not free.\n\n1. What if we can defer our path creation to later? That\'s good, but not enough because we would have to start our traversal from `beginWord` all over again.\n\n1. What about the **paths** we traversed via BFS? Most of them led to **dead-ends**. If only we don\'t have to traverse down these paths. **This is the crux of the optimization**. We can do this by traversing in reverse from `endWord` to `beginWord` instead!\n\n1. When we perform **BFS** (step 2), we construct a tree where the key is a `child` node and values are `parent` nodes. When `endWord` is found, the `wordTree` will contain a way to traverse from `endWord` to `beginWord`.\n\n1. Then we perform **DFS** on the `wordTree` and return our results.\n\np.s. this was **HARD** to figure out...rip if anyone ever needs to make this optimization in an interview.\n\n**Solution**\n```\nclass Solution:\n\n WILDCARD = "."\n \n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n """\n Given a wordlist, we perform BFS traversal to generate a word tree where\n every node points to its parent node.\n \n Then we perform a DFS traversal on this tree starting at the endWord.\n """\n if endWord not in wordList:\n # end word is unreachable\n return []\n \n # first generate a word tree from the wordlist\n word_tree = self.getWordTree(beginWord, endWord, wordList)\n \n # then generate a word ladder from the word tree\n return self.getLadders(beginWord, endWord, word_tree)\n \n \n def getWordTree(self,\n beginWord: str,\n endWord: str,\n wordList: List[str]) -> Dict[str, List[str]]:\n """\n BFS traversal from begin word until end word is encountered.\n \n This functions constructs a tree in reverse, starting at the endWord.\n """\n # Build an adjacency list using patterns as keys\n # For example: ".it" -> ("hit"), "h.t" -> ("hit"), "hi." -> ("hit")\n adjacency_list = defaultdict(list)\n for word in wordList:\n for i in range(len(word)):\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n adjacency_list[pattern].append(word)\n \n # Holds the tree of words in reverse order\n # The key is an encountered word.\n # The value is a list of preceding words.\n # For example, we got to beginWord from no other nodes.\n # {a: [b,c]} means we got to "a" from "b" and "c"\n visited_tree = {beginWord: []}\n \n # start off the traversal without finding the word\n found = False\n \n q = deque([beginWord])\n while q and not found:\n n = len(q)\n \n # keep track of words visited at this level of BFS\n visited_this_level = {}\n\n for i in range(n):\n word = q.popleft()\n \n for i in range(len(word)):\n # for each pattern of the current word\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n\n for next_word in adjacency_list[pattern]:\n if next_word == endWord:\n # we don\'t return immediately because other\n # sequences might reach the endWord in the same\n # BFS level\n found = True\n if next_word not in visited_tree:\n if next_word not in visited_this_level:\n visited_this_level[next_word] = [word]\n # queue up next word iff we haven\'t visited it yet\n # or already are planning to visit it\n q.append(next_word)\n else:\n visited_this_level[next_word].append(word)\n \n # add all seen words at this level to the global visited tree\n visited_tree.update(visited_this_level)\n \n return visited_tree\n \n \n def getLadders(self,\n beginWord: str,\n endWord: str,\n wordTree: Dict[str, List[str]]) -> List[List[str]]:\n """\n DFS traversal from endWord to beginWord in a given tree.\n """\n def dfs(node: str) -> List[List[str]]:\n if node == beginWord:\n return [[beginWord]]\n if node not in wordTree:\n return []\n\n res = []\n parents = wordTree[node]\n for parent in parents:\n res += dfs(parent)\n for r in res:\n r.append(node)\n return res\n\n return dfs(endWord)\n``` | 83 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Python'] | 8 |
word-ladder-ii | Use defaultdict for traceback and easy writing, 20 lines python code | use-defaultdict-for-traceback-and-easy-w-0rja | class Solution:\n # @param start, a string\n # @param end, a string\n # @param dict, a set of string\n # @return a list of lists of string\n def | tusizi | NORMAL | 2015-02-03T14:28:29+00:00 | 2018-10-05T02:05:09.316413+00:00 | 18,134 | false | class Solution:\n # @param start, a string\n # @param end, a string\n # @param dict, a set of string\n # @return a list of lists of string\n def findLadders(self, start, end, dic):\n dic.add(end)\n level = {start}\n parents = collections.defaultdict(set)\n while level and end not in parents:\n next_level = collections.defaultdict(set)\n for node in level:\n for char in string.ascii_lowercase:\n for i in range(len(start)):\n n = node[:i]+char+node[i+1:]\n if n in dic and n not in parents:\n next_level[n].add(node)\n level = next_level\n parents.update(next_level)\n res = [[end]]\n while res and res[0][0] != start:\n res = [[p]+r for r in res for p in parents[r[0]]]\n return res\n\nEvery level we use the defaultdict to get rid of the duplicates | 82 | 7 | ['Python'] | 15 |
word-ladder-ii | ✔️ Explanation with Animation - Accepted without TLE! | explanation-with-animation-accepted-with-zlxi | Intuition\nWe just need to record all possible words that can connect from the beginning, level by level, until we hit the end at a level.\n\n\n\nThen we will t | Sneeit-Dot-Com | NORMAL | 2022-08-14T14:25:11.290327+00:00 | 2022-08-28T02:20:30.676155+00:00 | 14,406 | false | # Intuition\nWe just need to record all possible words that can connect from the beginning, level by level, until we hit the end at a level.\n\n\n\nThen we will traverse backward from end via the words in the record and construct our final ways.\n\n**Remember:** we will not record paths, we record only nodes. \n\n_____\n# Explanation\nFirst, because we traverse level by level, so as soon as we see the end, that is the shortest distance (shortest path) we have from beginning. This is the basic theorem of BFS in an unweighted graph: https://sneeit.com/graph/?tab=documentation#breath-first-search-in-graph\n\nWhen we see the end, we know some of the nodes from previous level (which connect to the beginning because we traversed from there) are pointing to the end. We just need to move backward, level by level then we could collect all paths to end from begin\n_____\n# Why Other\'s Solutions Get TLE\nBecause if there are some nodes point to a same node, their solutions keep computing the same path again and again due to they see those paths are different (from the beginning node). This is the weakness of recording paths, instead of nodes.\n\nCheck the red node in the following figure for more information:\n\n\n\nIn summary:\n1. Other solutions:\n\t* Store paths, so every node could be stored multiple times.\n\t* Compute the intersections in paths again and again\n\t* Paths that does not lead to end also be computed\n2. My solution:\n\t* Store only nodes so every node is store exactly one time\n\t* Move backward to compute only the paths that can connect from begin to end\n\n_____\n# Algorithm\n* **Moving Forward: start from begin**\n\t1. Each level, find all connected nodes to the nodes of the current level in the record and add those to the record for the next level.\n\t2. Delete node from wordList to prevent revisiting and forming cycles\n\t3. Repeat the above steps until we reach end or we add no new nodes to the record for next level\n\n* **Moving Backward: start from end**\n\t1. Do the same steps as moving forward but this time we will not record nodes but contruct our paths\n\t2. Construct paths in reversing order to have paths from begin to end\n_____\n\n# Codes\n_____\n\n## JavaScript\n\n```\nvar findLadders = function(beginWord, endWord, wordList) {\n // to check if two words can connect\n let connected = (a,b) => {\n let c = 0\n for (let i = 0; i < a.length && c < 2; i++) {\n if (a[i] !== b[i]) c++\n }\n return c == 1\n }\n\n // dictionary to help us search words faster\n // and to trackback what word was used\n let dict = new Set(wordList);\n if (dict.has(endWord) == false) return []\n\n dict.delete(beginWord)\n let queue = [beginWord]\n let nodes = []\n\n \n // find all ways from beginning\n // level by level, until reach end at a level\n let reached = false; \n while (queue.length && !reached) {\n // update nodes of paths for this level\n nodes.push(queue.slice())\n\n // access whole level \n let qlen = queue.length;\n for (let i = 0; i < qlen && !reached; i++) {\n\n let from = queue.shift();\n \n // find all nodes that connect to the nodes of this level\n for (let to of dict) { \n\n if (connected(from,to) == false) continue\n\n // if connect\n // - and one of them is end word\n // - then we can stop moving forward\n if (to == endWord) {\n reached = true\n break;\n }\n\n // - otherwise,\n // - add all connected nodes to the record for the next level\n // - and delete them from dict to prevent revisiting to form cycles\n queue.push(to) \n dict.delete(to) \n }\n }\n }\n\n // try but did not find endWord\n if (!reached) return []\n\n // move backward to construct paths\n // add nodes to paths in reverse order to have paths from begin to end\n let ans = [[endWord]]\n for (let level = nodes.length - 1; level >= 0; level--) { \n let alen = ans.length\n for (let a = 0; a < alen; a++) {\n let p = ans.shift()\n let last = p[0] \n for (let word of nodes[level]) { \n if (!connected(last, word)) continue \n ans.push([word, ...p])\n }\n } \n }\n\n return ans\n}\n```\n\n____\n## C++\nThis is my first C++ code. Hope you can suggest optimizations . Thanks.\n```\nclass Solution {\npublic:\n bool isConnected(string s,string t){\n int c=0;\n for(int i=0;i<s.length();i++)\n c+=(s[i]!=t[i]);\n return c==1;\n }\n\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n vector<vector<string>> ans; \n vector<vector<string>> nodes; \n unordered_set<string> dict(wordList.begin(),wordList.end());\n \n if (!dict.count(endWord)) return ans;\n dict.erase(beginWord);\n \n \n bool reached = false;\n nodes.push_back({beginWord});\n \n while (dict.size() && !reached) { \n vector<string> last = nodes.back();\n vector<string> curr;\n \n for (int i = 0; i < last.size() && !reached; i++) {\n unordered_set<string> visited;\n string from = last[i]; \n // check all nodes that connect\n // to the nodes of the previous level \n for (auto& to : dict) { \n if (visited.count(to)) continue;\n if (!isConnected(from, to)) continue; \n // if one of them is "endWord" then we can stop \n // because this level is the shortest distance from begin\n if (to == endWord) { \n reached = true; \n break;\n }\n \n // otherwise,\n // add nodes for the current level\n curr.push_back(to); \n visited.insert(to); \n } \n // delete the visited to prevent forming cycles \n for (auto& visited : visited) { \n dict.erase(visited);\n }\n }\n \n // found endWord this level\n if (reached) break;\n \n // can not add any new nodes to our level\n if (!curr.size()) break;\n \n // otherwise, record all nodes for the current level\n nodes.push_back(curr); \n }\n \n // try but not find\n if (reached == false) return ans;\n \n // move backward\n ans.push_back({endWord}); \n for (int level = nodes.size() - 1; level >= 0; level--) { \n int alen = ans.size();\n while (alen) {\n vector<string> path = ans.back();\n ans.pop_back();\n string from = path.front(); \n for (string &to : nodes[level]) { \n if (!isConnected(from, to)) continue;\n \n vector<string> newpath = path;\n newpath.insert(newpath.begin(), to);\n ans.insert(ans.begin(), newpath);\n } \n alen--;\n } \n }\n return ans;\n }\n};\n```\n____\n## Pseudocode\n```\n// Pseudocode\nfunction findLadders(beginWord, endWord, wordList) {\n if (wordList.hasNo(endWord)) return []\n wordList.delete(beginWord)\n\n // move forward\n queue = [beginWord]\n paths = [] // 2D array\n reached = false; \n while (queue.length && !reached) {\n paths.append(queue) // deep copy\n \n // need static here to access only the nodes of this level\n qlen = queue.length; \n for (let i = 0; i < qlen && !reached; i++) {\n from = queue.takeFirst()\n forEach (to of wordList) {\n if (isConnected(from, to)) { \n if (to == endWord) {\n reached = true\n break // exit from the forEach\n }\n \n queue.push(to) \n wordList.delete(to) // delete to preven a cycle \n }\n }\n }\n }\n\n // can not reach the end eventually\n if (!reached) return []\n\n // move backward\n answer = [[endWord]] // 2D array \n for (level = paths.length - 1; level >= 0; level--) { \n path = paths[level]\n alen = answer.length\n for (a = 0; a < alen; a++) {\n p = answer.takeFirst()\n last = p[0]\n forEach (word of path) {\n if (!isConnected(last, word)) {\n answer.append([word, ...p])\n }\n \n }\n } \n }\n\n return answer\n}\n\n\n// to check if two words can connect\nfunction isConnected(a,b) {\n c = 0\n for (i = 0; i < a.length && c < 2; i++) {\n if (a[i] !== b[i]) c++\n }\n return c == 1\n}\n```\n\n____\n | 72 | 7 | ['Breadth-First Search', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 12 |
word-ladder-ii | C++ || No TLE || August 2022 || Simple BFS || Explained | c-no-tle-august-2022-simple-bfs-explaine-6b01 | Step 1:-\nCount the minimum steps required to reach beginword from each string present in the word list using simple BFS.\n\nStep 2:-\nThen for returning the pa | riyushhh | NORMAL | 2022-08-14T06:29:15.664524+00:00 | 2022-08-14T07:12:24.335213+00:00 | 6,627 | false | ***Step 1:-***\nCount the minimum steps required to reach **beginword** from each string present in the word list using simple BFS.\n\n**Step 2:-**\nThen for returning the path, start backtracking from the **endword** and keep moving to words having minimum steps 1 less than the current word.\n\n**Do upvote if you like it.**\n\n```\nclass Solution\n{\npublic:\n vector<vector<string>> res;\n vector<string> te;\n unordered_map<string, int> mp;\n string b;\n void dfs(string s) // Step 2\n {\n te.push_back(s);\n if (s == b)\n {\n vector<string> x = te;\n reverse(x.begin(), x.end());\n res.push_back(x);\n te.pop_back();\n return;\n }\n int cur = mp[s];\n for (int i = 0; i < s.size(); i++)\n {\n char c = s[i];\n for (char cc = \'a\'; cc <= \'z\'; cc++)\n {\n s[i] = cc;\n if (mp.count(s) && mp[s] == cur - 1)\n dfs(s);\n }\n s[i] = c;\n }\n te.pop_back();\n return;\n }\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wordList)\n {\n unordered_set<string> dict(wordList.begin(), wordList.end());\n b = beginWord;\n queue<string> q;\n int k = beginWord.size();\n q.push({beginWord});\n mp[beginWord] = 0;\n while (!q.empty()) // Step 1\n {\n int n = q.size();\n while (n--)\n {\n string t = q.front();\n q.pop();\n int x = mp[t] + 1;\n for (int i = 0; i < k; i++)\n {\n string temp = t;\n for (char ch = \'a\'; ch <= \'z\'; ch++)\n {\n temp[i] = ch;\n if (!mp.count(temp) && dict.count(temp))\n mp[temp] = x, q.push(temp);\n }\n }\n }\n }\n if (mp.count(endWord))\n dfs(endWord);\n return res;\n }\n};\n``` | 60 | 1 | [] | 12 |
word-ladder-ii | Simple Python BFS solution (similar problems listed) | simple-python-bfs-solution-similar-probl-al51 | Level-by-level BFS visit can be used to solve a lot of problems of finding discrete shortest distance.\nPlease see and vote for my solutions for these similar p | otoc | NORMAL | 2019-08-06T18:07:20.511298+00:00 | 2022-07-30T23:51:22.502956+00:00 | 5,393 | false | Level-by-level BFS visit can be used to solve a lot of problems of finding discrete shortest distance.\nPlease see and vote for my solutions for these similar problems\n[102. Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/1651394/Python-level-by-level-BFS-Solution)\n[127. Word Ladder](https://leetcode.com/problems/word-ladder/discuss/352659/Simple-Python-BFS-solution)\n[126. Word Ladder II](https://leetcode.com/problems/word-ladder-ii/discuss/352661/Simple-Python-BFS-solution)\n[301. Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/discuss/327481/Python-DFS-solution-with-pruning-(28-ms-beat-99.56)-%2B-BFS-solution)\n[317. Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings/discuss/331983/Python-BFS-solution-(52-ms-beat-98.27))\n[529. Minesweeper](https://leetcode.com/problems/minesweeper/discuss/1651414/python-level-by-level-bfs-solution)\n[773. Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle/discuss/412586/Standard-Python-BFS-solution-(level-by-level-traversal))\n[815. Bus Routes](https://leetcode.com/problems/bus-routes/discuss/1651399/Python-Level-by-level-BFS-solution)\n[854. K-Similar Strings](https://leetcode.com/problems/k-similar-strings/discuss/420506/Python-BFS-solution)\n[864. Shortest Path to Get All Keys](https://leetcode.com/problems/shortest-path-to-get-all-keys/discuss/364604/Simple-Python-BFS-Solution-(292-ms-beat-97.78))\n[1091. Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/313229/Python-BFS-solution)\n[1210. Minimum Moves to Reach Target with Rotations](https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/discuss/392940/Standard-Python-BFS-solution)\n[1263. Minimum Moves to Move a Box to Their Target Location](https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location/discuss/431138/Python-straightforward-BFS-solution)\n[1293. Shortest Path in a Grid with Obstacles Elimination](https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1651383/Python-level-by-level-BFS-Solution)\n\n\n```\n def findLadders(self, beginWord, endWord, wordList):\n wordList = set(wordList)\n if endWord not in wordList:\n return []\n # BFS visit\n curr_level = {beginWord}\n parents = collections.defaultdict(list)\n while curr_level:\n wordList -= curr_level\n next_level = set()\n for word in curr_level:\n for i in range(len(word)):\n for c in \'abcdefghijklmnopqrstuvwxyz\':\n new_word = word[:i] + c + word[i+1:]\n if new_word in wordList:\n next_level.add(new_word)\n parents[new_word].append(word)\n if endWord in next_level:\n break\n curr_level = next_level\n # DFS reconstruction\n res = []\n def dfs(word, path):\n if word == beginWord:\n path.append(word)\n res.append(path[::-1])\n else:\n for p_word in parents[word]:\n dfs(p_word, path + [word])\n dfs(endWord, [])\n return res\n``` | 60 | 0 | [] | 7 |
word-ladder-ii | 88ms! Accepted c++ solution with two-end BFS. 68ms for Word Ladder and 88ms for Word Ladder II | 88ms-accepted-c-solution-with-two-end-bf-ftmq | In order to reduce the running time, we should use two-end BFS to slove the problem.\n\nAccepted 68ms c++ solution for [Word Ladder][1].\n\n class Solution { | prime_tang | NORMAL | 2015-06-23T01:46:42+00:00 | 2015-06-23T01:46:42+00:00 | 31,919 | false | In order to reduce the running time, we should use two-end BFS to slove the problem.\n\nAccepted 68ms c++ solution for [Word Ladder][1].\n\n class Solution {\n public:\n int ladderLength(std::string beginWord, std::string endWord, std::unordered_set<std::string> &dict) {\n \t\tif (beginWord == endWord)\n \t\t\treturn 1;\n std::unordered_set<std::string> words1, words2;\n \t\twords1.insert(beginWord);\n \t\twords2.insert(endWord);\n dict.erase(beginWord);\n dict.erase(endWord);\n return ladderLengthHelper(words1, words2, dict, 1);\n }\n \n private:\n int ladderLengthHelper(std::unordered_set<std::string> &words1, std::unordered_set<std::string> &words2, std::unordered_set<std::string> &dict, int level) {\n \t\tif (words1.empty())\n return 0;\n \t\tif (words1.size() > words2.size())\n \t\t\treturn ladderLengthHelper(words2, words1, dict, level);\n std::unordered_set<std::string> words3;\n for (auto it = words1.begin(); it != words1.end(); ++it) {\n \t\t\tstd::string word = *it;\n \t\t\tfor (auto ch = word.begin(); ch != word.end(); ++ch) {\n \t\t\t\tchar tmp = *ch;\n for (*ch = 'a'; *ch <= 'z'; ++(*ch))\n \t\t\t\t\tif (*ch != tmp)\n \t\t\t\t\t\tif (words2.find(word) != words2.end())\n return level + 1;\n \t\t\t\t\t\telse if (dict.find(word) != dict.end()) {\n dict.erase(word);\n words3.insert(word);\n }\n \t\t\t\t*ch = tmp;\n }\n }\n return ladderLengthHelper(words2, words3, dict, level + 1);\n }\n };\n\nAccepted 88ms c++ solution for [Word Ladder II][2].\n\n class Solution {\n public:\n std::vector<std::vector<std::string> > findLadders(std::string beginWord, std::string endWord, std::unordered_set<std::string> &dict) {\n \t\tstd::vector<std::vector<std::string> > paths;\n \t\tstd::vector<std::string> path(1, beginWord);\n \t\tif (beginWord == endWord) {\n \t\t\tpaths.push_back(path);\n \t\t\treturn paths;\n \t\t}\n std::unordered_set<std::string> words1, words2;\n \t\twords1.insert(beginWord);\n \t\twords2.insert(endWord);\n \t\tstd::unordered_map<std::string, std::vector<std::string> > nexts;\n \t\tbool words1IsBegin = false;\n if (findLaddersHelper(words1, words2, dict, nexts, words1IsBegin))\n \t\t\tgetPath(beginWord, endWord, nexts, path, paths);\n \t\treturn paths;\n }\n private:\n bool findLaddersHelper(\n \t\tstd::unordered_set<std::string> &words1,\n \t\tstd::unordered_set<std::string> &words2,\n \t\tstd::unordered_set<std::string> &dict,\n \t\tstd::unordered_map<std::string, std::vector<std::string> > &nexts,\n \t\tbool &words1IsBegin) {\n \t\twords1IsBegin = !words1IsBegin;\n \t\tif (words1.empty())\n return false;\n \t\tif (words1.size() > words2.size())\n \t\t\treturn findLaddersHelper(words2, words1, dict, nexts, words1IsBegin);\n \t\tfor (auto it = words1.begin(); it != words1.end(); ++it)\n \t\t\tdict.erase(*it);\n \t\tfor (auto it = words2.begin(); it != words2.end(); ++it)\n \t\t\tdict.erase(*it);\n std::unordered_set<std::string> words3;\n \t\tbool reach = false;\n for (auto it = words1.begin(); it != words1.end(); ++it) {\n \t\t\tstd::string word = *it;\n \t\t\tfor (auto ch = word.begin(); ch != word.end(); ++ch) {\n \t\t\t\tchar tmp = *ch;\n for (*ch = 'a'; *ch <= 'z'; ++(*ch))\n \t\t\t\t\tif (*ch != tmp)\n \t\t\t\t\t\tif (words2.find(word) != words2.end()) {\n \t\t\t\t\t\t\treach = true;\n \t\t\t\t\t\t\twords1IsBegin ? nexts[*it].push_back(word) : nexts[word].push_back(*it);\n \t\t\t\t\t\t}\n \t\t\t\t\t\telse if (!reach && dict.find(word) != dict.end()) {\n \t\t\t\t\t\t\twords3.insert(word);\n \t\t\t\t\t\t\twords1IsBegin ? nexts[*it].push_back(word) : nexts[word].push_back(*it);\n }\n \t\t\t\t*ch = tmp;\n }\n }\n return reach || findLaddersHelper(words2, words3, dict, nexts, words1IsBegin);\n }\n \tvoid getPath(\n \t\tstd::string beginWord,\n \t\tstd::string &endWord,\n \t\tstd::unordered_map<std::string, std::vector<std::string> > &nexts,\n \t\tstd::vector<std::string> &path,\n \t\tstd::vector<std::vector<std::string> > &paths) {\n \t\tif (beginWord == endWord)\n \t\t\tpaths.push_back(path);\n \t\telse\n \t\t\tfor (auto it = nexts[beginWord].begin(); it != nexts[beginWord].end(); ++it) {\n \t\t\t\tpath.push_back(*it);\n \t\t\t\tgetPath(*it, endWord, nexts, path, paths);\n \t\t\t\tpath.pop_back();\n \t\t\t}\n \t}\n };\n\n\n [1]: https://leetcode.com/problems/word-ladder/\n [2]: https://leetcode.com/problems/word-ladder-ii/ | 52 | 1 | ['Breadth-First Search'] | 11 |
word-ladder-ii | 46ms Python 97 Faster Working Multiple solutions 95% memory efficient solution | 46ms-python-97-faster-working-multiple-s-08gc | Don\'t Forget To Upvote\n\n# 1. 97.81% Faster Solution:\n\n\t\tclass Solution:\n\t\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) - | anuvabtest | NORMAL | 2022-08-14T04:13:26.038470+00:00 | 2022-08-14T04:15:44.811499+00:00 | 6,898 | false | # Don\'t Forget To Upvote\n\n# 1. 97.81% Faster Solution:\n\n\t\tclass Solution:\n\t\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\t\td = defaultdict(list)\n\t\t\t\tfor word in wordList:\n\t\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\t\td[word[:i]+"*"+word[i+1:]].append(word)\n\n\t\t\t\tif endWord not in wordList:\n\t\t\t\t\treturn []\n\n\t\t\t\tvisited1 = defaultdict(list)\n\t\t\t\tq1 = deque([beginWord])\n\t\t\t\tvisited1[beginWord] = []\n\n\t\t\t\tvisited2 = defaultdict(list)\n\t\t\t\tq2 = deque([endWord])\n\t\t\t\tvisited2[endWord] = []\n\n\t\t\t\tans = []\n\t\t\t\tdef dfs(v, visited, path, paths):\n\t\t\t\t\tpath.append(v)\n\t\t\t\t\tif not visited[v]:\n\t\t\t\t\t\tif visited is visited1:\n\t\t\t\t\t\t\tpaths.append(path[::-1])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpaths.append(path[:])\n\t\t\t\t\tfor u in visited[v]:\n\t\t\t\t\t\tdfs(u, visited, path, paths)\n\t\t\t\t\tpath.pop()\n\n\t\t\t\tdef bfs(q, visited1, visited2, frombegin):\n\t\t\t\t\tlevel_visited = defaultdict(list)\n\t\t\t\t\tfor _ in range(len(q)):\n\t\t\t\t\t\tu = q.popleft()\n\n\t\t\t\t\t\tfor i in range(len(u)):\n\t\t\t\t\t\t\tfor v in d[u[:i]+"*"+u[i+1:]]:\n\t\t\t\t\t\t\t\tif v in visited2:\n\t\t\t\t\t\t\t\t\tpaths1 = []\n\t\t\t\t\t\t\t\t\tpaths2 = []\n\t\t\t\t\t\t\t\t\tdfs(u, visited1, [], paths1)\n\t\t\t\t\t\t\t\t\tdfs(v, visited2, [], paths2)\n\t\t\t\t\t\t\t\t\tif not frombegin:\n\t\t\t\t\t\t\t\t\t\tpaths1, paths2 = paths2, paths1\n\t\t\t\t\t\t\t\t\tfor a in paths1:\n\t\t\t\t\t\t\t\t\t\tfor b in paths2:\n\t\t\t\t\t\t\t\t\t\t\tans.append(a+b)\n\t\t\t\t\t\t\t\telif v not in visited1:\n\t\t\t\t\t\t\t\t\tif v not in level_visited:\n\t\t\t\t\t\t\t\t\t\tq.append(v)\n\t\t\t\t\t\t\t\t\tlevel_visited[v].append(u)\n\t\t\t\t\tvisited1.update(level_visited)\n\n\t\t\t\twhile q1 and q2 and not ans:\n\t\t\t\t\tif len(q1) <= len(q2):\n\t\t\t\t\t\tbfs(q1, visited1, visited2, True)\n\t\t\t\t\telse:\n\t\t\t\t\t\tbfs(q2, visited2, visited1, False)\n\n\t\t\t\treturn ans\n\t\t\t\t\n\t\t\t\t\n# 2. 87% fast solution a little different approach:\n\n\n\t\tclass Solution:\n\t\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\t\tres = []\n\t\t\t\tedge = collections.defaultdict(set)\n\t\t\t\twordList = set(wordList)\n\t\t\t\tfor word in wordList:\n\t\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\t\tedge[word[:i] +\'*\'+word[i+1:]].add(word)\n\t\t\t\tbfsedge = {}\n\n\t\t\t\tdef bfs():\n\t\t\t\t\tminl = 0\n\t\t\t\t\tqueue = set()\n\t\t\t\t\tqueue.add(beginWord)\n\t\t\t\t\twhile queue:\n\t\t\t\t\t\tnext_queue = set()\n\t\t\t\t\t\tfor word in queue:\n\t\t\t\t\t\t\tif word in wordList:\n\t\t\t\t\t\t\t\twordList.remove(word)\n\t\t\t\t\t\tbfsedge[minl] = collections.defaultdict(set)\n\t\t\t\t\t\tfor word in queue:\n\t\t\t\t\t\t\tif word == endWord:\n\t\t\t\t\t\t\t\treturn minl\n\t\t\t\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\t\t\t\tfor w in edge[word[:i]+\'*\'+word[i+1:]]:\n\t\t\t\t\t\t\t\t\tif w in wordList:\n\t\t\t\t\t\t\t\t\t\tnext_queue.add(w)\n\t\t\t\t\t\t\t\t\t\tbfsedge[minl][w].add(word)\n\t\t\t\t\t\tqueue = next_queue\n\t\t\t\t\t\tminl += 1\n\t\t\t\t\treturn minl\n\n\t\t\t\tdef dfs(seq, endWord):\n\t\t\t\t\tif seq[-1] == endWord:\n\t\t\t\t\t\tres.append(seq.copy())\n\t\t\t\t\t\treturn\n\t\t\t\t\tfor nextWord in bfsedge[minl-len(seq)][seq[-1]]:\n\t\t\t\t\t\tif nextWord not in seq:\n\t\t\t\t\t\t\tdfs(seq+[nextWord], endWord)\n\n\t\t\t\tminl = bfs()\n\t\t\t\tdfs([endWord], beginWord)\n\t\t\t\t# reverse the sequence\n\t\t\t\tfor sq in res:\n\t\t\t\t\tsq.reverse()\n\t\t\t\treturn res\n\t\t\t\t\n\t\t\t\t\n# 3.95% Memory efficient solution:\n\t\tfrom collections import deque\n\t\tclass Solution:\n\t\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\t\tif endWord not in wordList:return []\n\t\t\t\twordList.append(beginWord)\n\t\t\t\twordList.append(endWord)\n\t\t\t\tdistance = {}\n\n\n\t\t\t\tself.bfs(endWord, distance, wordList)\n\n\t\t\t\tresults = []\n\t\t\t\tself.dfs(beginWord, endWord, distance, wordList, [beginWord], results)\n\n\t\t\t\treturn results\n\n\t\t\tdef bfs(self, start, distance, w):\n\t\t\t\tdistance[start] = 0\n\t\t\t\tqueue = deque([start])\n\t\t\t\twhile queue:\n\t\t\t\t\tword = queue.popleft()\n\t\t\t\t\tfor next_word in self.get_next_words(word, w):\n\t\t\t\t\t\tif next_word not in distance:\n\t\t\t\t\t\t\tdistance[next_word] = distance[word] + 1\n\t\t\t\t\t\t\tqueue.append(next_word)\n\n\t\t\tdef get_next_words(self, word, w):\n\t\t\t\twords = []\n\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\tfor c in \'abcdefghijklmnopqrstuvwxyz\':\n\t\t\t\t\t\tnext_word = word[:i] + c + word[i + 1:]\n\t\t\t\t\t\tif next_word != word and next_word in w:\n\t\t\t\t\t\t\twords.append(next_word)\n\t\t\t\treturn words\n\n\t\t\tdef dfs(self, curt, target, distance, w, path, results):\n\t\t\t\tif curt == target:\n\t\t\t\t\tresults.append(list(path))\n\t\t\t\t\treturn\n\n\t\t\t\tfor word in self.get_next_words(curt, w):\n\t\t\t\t\tif distance[word] != distance[curt] - 1:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tpath.append(word)\n\t\t\t\t\tself.dfs(word, target, distance, w, path, results)\n\t\t\t\t\tpath.pop()\n | 49 | 3 | ['Depth-First Search', 'Breadth-First Search', 'Queue', 'Python', 'Python3'] | 8 |
word-ladder-ii | C++ very easy read and understand solution compared to most voted! | c-very-easy-read-and-understand-solution-n99f | For the most voted solution, it is very complicated.\nI do a BFS for each path\nfor example: \n{hit} -> \n{hit,hot} ->\n {hit,hot,dot}/{hit,hot,lot} -> \n ["hit | rayrayray | NORMAL | 2017-08-10T20:31:58.982000+00:00 | 2018-08-21T20:23:05.055655+00:00 | 6,551 | false | For the most voted solution, it is very complicated.\nI do a BFS for each path\nfor example: \n{hit} -> \n{hit,hot} ->\n {hit,hot,dot}/{hit,hot,lot} -> \n ["hit","hot","dot","dog"]/["hit","hot","lot","log"] ->\n ["hit","hot","dot","dog","cog"],\n ["hit","hot","lot","log","cog"]\n```\nclass Solution {\npublic:\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n vector<vector<string>> res;\n unordered_set<string> visit; //notice we need to clear visited word in list after finish this level of BFS\n queue<vector<string>> q;\n unordered_set<string> wordlist(wordList.begin(),wordList.end());\n q.push({beginWord});\n bool flag= false; //to see if we find shortest path\n while(!q.empty()){\n int size= q.size();\n for(int i=0;i<size;i++){ //for this level\n vector<string> cur = q.front();\n q.pop();\n vector<string> newadd = addWord(cur.back(),wordlist); \n for(int j=0;j<newadd.size();j++){ //add a word into path\n vector<string> newline(cur.begin(),cur.end());\n newline.push_back(newadd[j]);\n if(newadd[j]==endWord){ \n flag=true;\n res.push_back(newline);\n }\n visit.insert(newadd[j]);\n q.push(newline);\n }\n }\n if(flag) break; //do not BFS further \n for(auto it=visit.begin();it!=visit.end();it++) wordlist.erase(*it); //erase visited one \n visit.clear();\n }\n return res;\n }\n \n // find words with one char different in dict\n // hot->[dot,lot]\n vector<string> addWord( string word,unordered_set<string>& wordlist ){\n vector<string> res;\n for(int i=0;i<word.size();i++){\n char s =word[i];\n for(char c='a';c<='z';c++){\n word[i]=c;\n if(wordlist.count(word)) res.push_back(word);\n }\n word[i]=s;\n }\n return res;\n }\n};\n``` | 46 | 3 | [] | 14 |
word-ladder-ii | The fastest C++ Solution, 56ms!! | the-fastest-c-solution-56ms-by-missmary-lv5a | Treat each word as a node of a tree. There are two trees. One tree's root node is "beginWord", and the other tree's root node is "endWord".\n\nThe root node can | missmary | NORMAL | 2015-09-26T12:52:51+00:00 | 2018-10-07T12:59:44.228536+00:00 | 19,335 | false | Treat each word as a node of a tree. There are two trees. One tree's root node is "beginWord", and the other tree's root node is "endWord".\n\nThe root node can yield all his children node, and they are the second layer of the tree. The second layer can yield all their children, then we get the third layer of the tree, ... , and so on.\n\nWhen one tree yield a new child, we search it in the last layer of the other tree. If we find an identical node in that tree, then we get some ladders connect two roots("beginWord" -> ... -> "endWord").\n\nAnother thing should be considered is: two(or more) different nodes may yield an identical child. That means the child may have two(or more) parents. For example, "hit" and "hot" can both yield "hat", means "hat" has two parents.\n\nSo, the data struct of tree-node is:\n\n class Node {\n public: \n string word;\n vectror<Node*> parents;\n Node(string w) : word(w) {}\n }\n\nNote: we don't need a `children` field for `Node` class, because we won't use it.\n\nTwo nodes are considered equal when their `word` field are equal. So we introduce an compare function:\n\n bool nodecmp(Node* pa, Node* pb)\n {\n return pa->word < pb->word;\n }\n\nThen we use `nodecmp` as the compare function to build a node set.\n\n typedef bool (*NodeCmper) (Node*, Node*);\n typedef set<Node*, NodeCmper> NodeSet;\n NodeSet layer(nodecmp);\n\nThen we can store/search pointers of nodes in node set `layer`. For example:\n\n Node node1("hit"), node2("hot"), node3("hat"); \n layer.insert(&node1);\n layer.insert(&node2);\n layer.insert(&node3);\n auto itr = layer.find(new Node("hot"));\n cout << (*itr)->word; // output: hot\n\nUsing these data structures, we can solve this problem with bi-direction BFS algorithm. Below is the AC code, and it is very very fast.\n\n class Node;\n \n typedef vector<string> Ladder;\n typedef unordered_set<string> StringSet;\n typedef bool (*NodeCmper) (Node*, Node*);\n typedef set<Node*, NodeCmper> NodeSet;\n \n class Node\n {\n public:\n string word;\n vector<Node*> parents;\n \n Node(string w) : word(w) {}\n void addparent(Node* parent) { parents.push_back(parent); }\n \n // Yield all children of this node, and:\n // 1) If the child is found in $targetlayer, which means we found ladders that\n // connect BEGIN-WORD and END-WORD, then we get all paths through this node\n // to its ROOT node, and all paths through the target child node to its ROOT\n // node, and combine the two group of paths to a group of ladders, and append\n // these ladders to $ladders.\n // 2) Elif the $ladders is empty:\n // 2.1) If the child is found in $nextlayer, then get that child, and add\n // this node to its parents.\n // 2.2) Else, add the child to nextlayer, and add this node to its parents.\n // 3) Else, do nothing.\n void yieldchildren(NodeSet& nextlayer, StringSet& wordlist, NodeSet& targetlayer,\n vector<Ladder>& ladders, bool forward)\n {\n string nextword = word;\n for (int i = 0, n = nextword.length(); i < n; i++) {\n char oldchar = nextword[i];\n for (nextword[i] = 'a'; nextword[i] <= 'z'; nextword[i]++) {\n if (wordlist.count(nextword)) {\n // now we found a valid child-word, let's yield a child.\n Node* child = new Node(nextword);\n yield1(child, nextlayer, targetlayer, ladders, forward);\n }\n }\n nextword[i] = oldchar;\n }\n }\n \n // yield one child, see comment of function `yieldchildren`\n void yield1(Node* child, NodeSet& nextlayer, NodeSet& targetlayer,\n vector<Ladder>& ladders, bool forward) {\n auto itr = targetlayer.find(child);\n if (itr != targetlayer.end()) {\n for (Ladder path1 : this->getpaths()) {\n for (Ladder path2 : (*itr)->getpaths()) {\n if (forward) {\n ladders.push_back(path1);\n ladders.back().insert(ladders.back().end(), path2.rbegin(), path2.rend());\n } else {\n ladders.push_back(path2);\n ladders.back().insert(ladders.back().end(), path1.rbegin(), path1.rend());\n }\n }\n }\n } else if (ladders.empty()) {\n auto itr = nextlayer.find(child);\n if (itr != nextlayer.end()) {\n (*itr)->addparent(this);\n } else {\n child->addparent(this);\n nextlayer.insert(child);\n }\n }\n }\n \n vector<Ladder> getpaths()\n {\n vector<Ladder> ladders;\n if (parents.empty()) {\n ladders.push_back(Ladder(1, word));\n } else {\n for (Node* parent : parents) {\n for (Ladder ladder : parent->getpaths()) {\n ladders.push_back(ladder);\n ladders.back().push_back(word);\n }\n }\n }\n return ladders;\n }\n };\n \n bool nodecmp(Node* pa, Node* pb)\n {\n return pa->word < pb->word;\n }\n \n class Solution {\n public:\n vector<Ladder> findLadders(string begin, string end, StringSet& wordlist) {\n vector<Ladder> ladders;\n Node headroot(begin), tailroot(end);\n NodeSet frontlayer(nodecmp), backlayer(nodecmp);\n NodeSet *ptr_layerA = &frontlayer, *ptr_layerB = &backlayer;\n bool forward = true;\n \n if (begin == end) {\n ladders.push_back(Ladder(1, begin));\n return ladders;\n }\n \n frontlayer.insert(&headroot);\n backlayer.insert(&tailroot);\n wordlist.insert(end);\n while (!ptr_layerA->empty() && !ptr_layerB->empty() && ladders.empty()) {\n NodeSet nextlayer(nodecmp);\n if (ptr_layerA->size() > ptr_layerB->size()) {\n swap(ptr_layerA, ptr_layerB);\n forward = ! forward;\n }\n for (Node* node : *ptr_layerA) {\n wordlist.erase(node->word);\n }\n for (Node* node : *ptr_layerA) {\n node->yieldchildren(nextlayer, wordlist, *ptr_layerB, ladders, forward);\n }\n swap(*ptr_layerA, nextlayer);\n }\n \n return ladders;\n }\n }; | 45 | 2 | [] | 5 |
word-ladder-ii | FAST AND CLEAN Python/C++ Solution using Double BFS, beats 98% | fast-and-clean-pythonc-solution-using-do-1ypd | If we know source and destination, we can build the word tree by going forward in one direction and backwards in the other. We stop when we have found that a wo | agave | NORMAL | 2016-04-25T02:53:08+00:00 | 2018-10-26T06:58:43.454703+00:00 | 16,071 | false | If we know source and destination, we can build the word tree by going forward in one direction and backwards in the other. We stop when we have found that a word in the next level of BFS is in the other level, but first we need to update the tree for the words in the current level.\n\nThen we build the result by doing a DFS on the tree constructed by the BFS.\n\nThe difference between normal and double BFS is that the search changes from `O(k^d)` to `O(k^(d/2) + k^(d/2))`. Same complexity class, right? Yeah, tell it to the Facebook guys that have to search in graphs with hundreds of thousands of nodes. \n\n```\nclass Solution(object):\n\n # Solution using double BFS\n\n def findLadders(self, begin, end, words_list):\n \n def construct_paths(source, dest, tree):\n if source == dest: \n return [[source]]\n return [[source] + path for succ in tree[source]\n for path in construct_paths(succ, dest, tree)]\n\n def add_path(tree, word, neigh, is_forw):\n if is_forw: tree[word] += neigh,\n else: tree[neigh] += word,\n\n def bfs_level(this_lev, oth_lev, tree, is_forw, words_set):\n if not this_lev: return False\n if len(this_lev) > len(oth_lev):\n return bfs_level(oth_lev, this_lev, tree, not is_forw, words_set)\n for word in (this_lev | oth_lev):\n words_set.discard(word)\n next_lev, done = set(), False\n while this_lev:\n word = this_lev.pop()\n for c in string.ascii_lowercase:\n for index in range(len(word)):\n neigh = word[:index] + c + word[index+1:]\n if neigh in oth_lev:\n done = True\n add_path(tree, word, neigh, is_forw) \n if not done and neigh in words_set:\n next_lev.add(neigh)\n add_path(tree, word, neigh, is_forw)\n return done or bfs_level(next_lev, oth_lev, tree, is_forw, words_set)\n \n tree, path, paths = collections.defaultdict(list), [begin], []\n is_found = bfs_level(set([begin]), set([end]), tree, True, words_list)\n return construct_paths(begin, end, tree)\n```\n\n\nC++ code:\n\n```\nvoid add_to_tree(map<string, vector<string>>& tree, \n string word, \n string neigh, \n bool forward) {\n if (forward) tree[word].push_back(neigh);\n else tree[neigh].push_back(word);\n\n}\n\nvector<vector<string>> construct_paths(map<string, \n vector<string>>& tree, \n string start, \n string dest) {\n if (start == dest) {\n vector<string> res = {start};\n vector<vector<string>> arr = {res};\n return arr;\n }\n vector<vector<string>> result;\n\n for (auto succ: tree[start]) {\n for (auto path: construct_paths(tree, succ, dest)) {\n path.insert(path.begin(), start);\n result.push_back(path);\n }\n }\n return result;\n}\n\nbool bfs_levels(unordered_set<string>& now, \n unordered_set<string>& oth, \n bool& forward, \n map<string, vector<string>>& tree, \n unordered_set<string>& words_list,\n vector<char>& alphabet) {\n\n if (not now.size()) return false;\n if (now.size() > oth.size()){\n forward = not forward;\n return bfs_levels(oth, now, forward, tree, words_list, alphabet);\n }\n for (auto word: now) words_list.erase(word);\n for (auto word: oth) words_list.erase(word);\n \n bool done = false; unordered_set<string> next;\n\n for (string word: now) {\n for (int i = 0; i < word.size(); i++) {\n for (char c: alphabet) {\n auto neigh = word.substr(0, i) + c + word.substr(i+1);\n if (oth.count(neigh) > 0) {\n done = true;\n add_to_tree(tree, word, neigh, forward);\n }\n else {\n if (not done and words_list.count(neigh) > 0) {\n next.insert(neigh);\n add_to_tree(tree, word, neigh, forward);\n }\n }\n }\n }\n }\n forward = not forward;\n return done or bfs_levels(oth, next, forward, tree, words_list, alphabet);\n}\n\n\nclass Solution {\npublic:\n vector<vector<string>> findLadders(string beginWord, \n string endWord, \n unordered_set<string> &wordList) {\n\n vector<char> alphabet(26);\n std::iota(alphabet.begin(), alphabet.end(), 'a');\n unordered_set<string> now = {beginWord}, oth = {endWord};\n map<string, vector<string>> tree; bool forward = true;\n auto is_found = bfs_levels(now, oth, forward, tree, wordList, alphabet);\n return construct_paths(tree, beginWord, endWord); \n \n }\n};\n``` | 42 | 2 | ['Breadth-First Search', 'Python'] | 7 |
word-ladder-ii | JAVA || EASY || EXPLANATION || COMMENTED | java-easy-explanation-commented-by-jaska-k8n5 | Upvote if it helped\n\n\nclass Solution {\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n List<Li | jaskarans880 | NORMAL | 2022-08-14T02:01:41.795085+00:00 | 2022-08-14T02:01:41.795119+00:00 | 9,759 | false | Upvote if it helped\n\n```\nclass Solution {\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n List<List<String>> ans = new ArrayList<>(); \n Map<String, Set<String>> reverse = new HashMap<>(); // reverse graph start from endWord\n Set<String> wordSet = new HashSet<>(wordList); // remove the duplicate words\n wordSet.remove(beginWord); // remove the first word to avoid cycle path\n Queue<String> queue = new LinkedList<>(); // store current layer nodes\n queue.add(beginWord); // first layer has only beginWord\n Set<String> nextLevel = new HashSet<>(); // store nextLayer nodes\n boolean findEnd = false; // find endWord flag\n while (!queue.isEmpty()) { // traverse current layer nodes\n String word = queue.remove();\n for (String next : wordSet) {\n if (isLadder(word, next)) { // is ladder words\n\t\t\t\t\t// construct the reverse graph from endWord\n Set<String> reverseLadders = reverse.computeIfAbsent(next, k -> new HashSet<>());\n reverseLadders.add(word); \n if (endWord.equals(next)) {\n findEnd = true;\n }\n nextLevel.add(next); // store next layer nodes\n }\n }\n if (queue.isEmpty()) { // when current layer is all visited\n if (findEnd) break; // if find the endWord, then break the while loop\n queue.addAll(nextLevel); // add next layer nodes to queue\n wordSet.removeAll(nextLevel); // remove all next layer nodes in wordSet\n nextLevel.clear();\n }\n }\n if (!findEnd) return ans; // if can\'t reach endWord from startWord, then return ans.\n Set<String> path = new LinkedHashSet<>();\n path.add(endWord);\n\t\t// traverse reverse graph from endWord to beginWord\n findPath(endWord, beginWord, reverse, ans, path); \n return ans;\n }\n\n\n private void findPath(String endWord, String beginWord, Map<String, Set<String>> graph,\n List<List<String>> ans, Set<String> path) {\n Set<String> next = graph.get(endWord);\n if (next == null) return;\n for (String word : next) {\n path.add(word);\n if (beginWord.equals(word)) {\n List<String> shortestPath = new ArrayList<>(path);\n Collections.reverse(shortestPath); // reverse words in shortest path\n ans.add(shortestPath); // add the shortest path to ans.\n } else {\n findPath(word, beginWord, graph, ans, path);\n }\n path.remove(word);\n }\n }\n\n private boolean isLadder(String s, String t) {\n if (s.length() != t.length()) return false;\n int diffCount = 0;\n int n = s.length();\n for (int i = 0; i < n; i++) {\n if (s.charAt(i) != t.charAt(i)) diffCount++;\n if (diffCount > 1) return false;\n }\n return diffCount == 1;\n }\n}\n``` | 40 | 2 | ['Java'] | 9 |
word-ladder-ii | [Python] fast bfs, explained | python-fast-bfs-explained-by-dbabichev-ct51 | The idea of this problem is to run bfs, where one step is changing some letter of word. For me easier to separate problem to two parts:\n\n1. Create graph of co | dbabichev | NORMAL | 2021-07-24T08:02:35.186256+00:00 | 2021-07-24T12:35:32.789801+00:00 | 1,318 | false | The idea of this problem is to run bfs, where one step is changing some letter of word. For me easier to separate problem to two parts:\n\n1. Create graph of connections `G`.\n2. Run bfs on this graph with collecting all possible solutions.\n\nNow, let us consider steps in more details.\n\n1. To create graph of connections for each word, for example `hit`, create patterns `*it, h*t, hi*`. Then iterate over patterns and connect words in our defaultdict `G`.\n\n2. We need to run bfs, but we also need to give as answer all possible solutions, so, we need to modify our algorithm a bit. We keep two dictionaries: `deps` for depths of each word and `paths` to keep all possible paths. When we extract element from queue and look at its neighbours, we need to add new element to queue if `deps[neib] == -1`. Also we need to update `paths[neib]` if `deps[neib] == -1 or deps[neib] == deps[w] + `, that is to deal with all ways of optimal length.\n\n#### Complexity\nWe need `O(nk^2)` time to create all possible patterns: for each of `n` words we have `k` patterns with length `k`. Then we will have no more than `O(n*k*26)` possible connections for all pairs of words, each of which has length `k`, so to create `G` we need `O(nk^2*26)` time. In practice thought this number is smaller, because graph can not have this number of connections. For the last part with bfs we have complexity `O(nk^2*26)` again, because this is the number of edges in our graph + `A`, where `A` is number of found solutions, which can be exponential. So, time complexity is `O(nk^2*26 + A)`, space is the same.\n\n#### Code\n```python\nclass Solution:\n def findLadders(self, begW, endW, wordList):\n wordList += [begW]\n n, k = len(wordList), len(wordList[0])\n patterns = defaultdict(set)\n for word in wordList:\n for ind in range(0, k):\n tmp = word[0:ind] + "*" + word[ind+1:]\n patterns[tmp].add(word)\n \n G = defaultdict(set)\n for elem in patterns.values():\n for x, y in permutations(elem, 2):\n G[x].add(y)\n \n deps = {w: -1 for w in wordList}\n deps[begW] = 0\n paths = defaultdict(list)\n paths[begW] = [[begW]]\n queue = deque([begW])\n\n while queue:\n w = queue.popleft()\n if w == endW: return paths[w]\n for neib in G[w]:\n if deps[neib] == -1 or deps[neib] == deps[w] + 1:\n if deps[neib] == -1:\n queue.append(neib)\n deps[neib] = deps[w] + 1\n for elem in paths[w]:\n paths[neib].append(elem + [neib])\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 33 | 2 | ['Breadth-First Search'] | 5 |
word-ladder-ii | C++ Solution || Using BFS & DFS | c-solution-using-bfs-dfs-by-kannu_priya-r3uq | \nclass Solution {\npublic:\n vector<vector<string>> ans;\n void DFS(string &beginWord, string &endWord, unordered_map<string, unordered_set<string>>&adj, | kannu_priya | NORMAL | 2021-07-24T18:08:06.533653+00:00 | 2021-07-24T18:08:06.533696+00:00 | 3,936 | false | ```\nclass Solution {\npublic:\n vector<vector<string>> ans;\n void DFS(string &beginWord, string &endWord, unordered_map<string, unordered_set<string>>&adj, vector<string>&path){\n path.push_back(beginWord);\n if(beginWord == endWord){\n ans.push_back(path);\n path.pop_back();\n return;\n }\n for(auto x : adj[beginWord])\n DFS(x, endWord, adj, path);\n \n path.pop_back(); //pop current word to backtrack\n }\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n unordered_map<string,unordered_set<string>>adj; //adjacency list\n unordered_set<string> dict(wordList.begin(), wordList.end()); //insert all the strings in set\n \n\t\t//step-1 => Find min depth using BFS\n queue<string>q; //for BFS Traversal\n q.push(beginWord);\n unordered_map<string,int>visited;\n visited[beginWord] = 0; //start node will always at level 0\n \n while(!q.empty()){\n string curr = q.front();\n q.pop();\n string temp = curr;\n \n for(int i = 0; i < curr.size(); i++){ //check all characters\n for(char c = \'a\'; c <= \'z\'; c++){ //try all possible 26 letters\n if(temp[i] == c) continue; //skip if letter is same as original word\n temp[i] = c;\n \n if(dict.count(temp) > 0){ // check if new word is present in wordList\n if(visited.count(temp) == 0){ //check if new word was already visited\n visited[temp] = visited[curr] + 1;\n q.push(temp);\n adj[curr].insert(temp);\n }\n else if(visited[temp] == visited[curr] + 1) //if already visited and new word is child\n adj[curr].insert(temp); \n }\n }\n temp[i] = curr[i]; //revert back temp to curr\n }\n }\n // step-2 => find all min depth possible paths using DFS\n vector<string>path;\n DFS(beginWord, endWord, adj, path);\n return ans;\n }\n};\n``` | 26 | 2 | ['Depth-First Search', 'Breadth-First Search', 'C', 'C++'] | 5 |
word-ladder-ii | Clean but the best-submission (68ms) in C++, well-commented | clean-but-the-best-submission-68ms-in-c-rklde | class Solution \n {\n public:\n vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &dict) {\n | lhearen | NORMAL | 2016-03-25T12:34:00+00:00 | 2016-03-25T12:34:00+00:00 | 9,492 | false | class Solution \n {\n public:\n vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &dict) {\n vector<vector<string> > paths;\n vector<string> path(1, beginWord);\n if (beginWord == endWord) //corner case;\n {\n paths.push_back(path);\n return paths;\n }\n unordered_set<string> forward, backward;\n forward.insert(beginWord);\n backward.insert(endWord);\n unordered_map<string, vector<string> > tree;\n bool reversed = false; //make sure the tree generating direction is consistent, since we have to start from the smaller set to accelerate;\n if (buildTree(forward, backward, dict, tree, reversed))\n getPath(beginWord, endWord, tree, path, paths);\n return paths;\n }\n private:\n bool buildTree(unordered_set<string> &forward, unordered_set<string> &backward, unordered_set<string> &dict, unordered_map<string, vector<string> > &tree, bool reversed) \n {\n if (forward.empty()) return false;\n if (forward.size() > backward.size()) \n return buildTree(backward, forward, dict, tree, !reversed);\n for (auto &word: forward) dict.erase(word);\n for (auto &word: backward) dict.erase(word);\n unordered_set<string> nextLevel;\n bool done = false; //in case of invalid further searching;\n for (auto &it: forward) //traverse each word in the forward -> the current level of the tree;\n {\n string word = it;\n for (auto &c: word) \n {\n char c0 = c; //store the original;\n for (c = 'a'; c <= 'z'; ++c) //try each case;\n {\n if (c != c0) //avoid futile checking;\n {\n if (backward.count(word)) //using count is an accelerating method;\n {\n done = true;\n !reversed ? tree[it].push_back(word) : tree[word].push_back(it); //keep the tree generation direction consistent;\n }\n else if (!done && dict.count(word))\n {\n nextLevel.insert(word);\n !reversed ? tree[it].push_back(word) : tree[word].push_back(it);\n }\n }\n }\n c = c0; //restore the word;\n }\n }\n return done || buildTree(nextLevel, backward, dict, tree, reversed);\n }\n \n void getPath(string &beginWord, string &endWord, unordered_map<string, vector<string> > &tree, vector<string> &path, vector<vector<string> > &paths) //using reference can accelerate;\n {\n if (beginWord == endWord) paths.push_back(path); //till the end;\n else\n {\n for (auto &it: tree[beginWord]) \n {\n path.push_back(it);\n getPath(it, endWord, tree, path, paths); //DFS retrieving the path;\n path.pop_back();\n }\n }\n }\n }; | 25 | 3 | ['C++'] | 6 |
word-ladder-ii | 💯✅I spent 3 hours developing this fastest approach. Check it out and don't forget to drop a like💯✅ | i-spent-3-hours-developing-this-fastest-kbze3 | Must ReadEver tried finding a ladder in a word transformation problem? It's like playing hide and seek with your vocabulary—except the words are sneaky, and the | Ajay_Kartheek | NORMAL | 2025-01-23T13:28:08.517370+00:00 | 2025-01-23T13:28:08.517370+00:00 | 4,239 | false | # Must Read
**Ever tried finding a ladder in a word transformation problem? It's like playing hide and seek with your vocabulary—except the words are sneaky, and the only thing getting transformed is your sanity. It took me a solid 3 hours of coding to come up this solution, during which I conjured up 5 different approaches. I faced TLE three times and MLE twice After some serious optimization, I finally tamed the beast. Who knew word ladders could be such a workout for the brain?**
# Intuition
The problem at hand is to find all the shortest transformation sequences from a beginWord to an endWord using a given list of words (wordList). Each transformation can only change one letter at a time, and each transformed word must exist in the wordList. The solution employs a breadth-first search (BFS) to explore all possible transformations and a depth-first search (DFS) to backtrack and construct the valid paths.
# Approach
1. BFS for Shortest Path:
- Use BFS to explore all possible transformations from the beginWord.
- Maintain a depthMap to record the minimum number of transformations required to reach each word.
- If the endWord is reached during BFS, the search stops, and the depth of the endWord is noted.
2. DFS for Path Construction:
- Once the BFS is complete, use DFS to backtrack from the endWord to the beginWord, constructing all valid paths that match the minimum transformation depth recorded in depthMap.
- Each valid path is stored in the result list.
3. Word Transformation:
- For each word, generate all possible transformations by changing one letter at a time and check if the transformed word exists in the wordList.
# Complexity
- Time complexity:
O(N * M * 26)
- Space complexity:
O(N + M)
# Code
```python3 []
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
depthMap = {}
ans = []
def dfs(word, seq):
if word == beginWord:
ans.append(seq[::-1])
return
steps = depthMap[word]
for i in range(len(word)):
original = word[i]
for ch in 'abcdefghijklmnopqrstuvwxyz':
word = word[:i] + ch + word[i+1:]
if word in depthMap and depthMap[word] + 1 == steps:
seq.append(word)
dfs(word, seq)
seq.pop()
word = word[:i] + original + word[i+1:]
wordSet = set(wordList)
q = deque([beginWord])
depthMap[beginWord] = 1
wordSet.discard(beginWord)
while q:
word = q.popleft()
steps = depthMap[word]
if word == endWord:
break
for i in range(len(word)):
original = word[i]
for ch in 'abcdefghijklmnopqrstuvwxyz':
word = word[:i] + ch + word[i+1:]
if word in wordSet:
q.append(word)
wordSet.discard(word)
depthMap[word] = steps + 1
word = word[:i] + original + word[i+1:]
if endWord in depthMap:
seq = [endWord]
dfs(endWord, seq)
return ans
# queue = deque([[beginWord]])
# wordSet = set(wordList)
# visited = set()
# res = []
# patterns = defaultdict(list)
# for word in wordList:
# for i in range(len(word)):
# curPattern = word[:i] + "*" + word[i + 1:]
# patterns[curPattern].append(word)
# while queue:
# currLayer = set()
# for _ in range(len(queue)):
# curList = queue.popleft()
# lastWord = curList[-1]
# if lastWord == endWord:
# res.append(curList)
# for i in range(len(lastWord)):
# newWord = lastWord[:i] + "*" + lastWord[i + 1:]
# for pattern in patterns[newWord]:
# if pattern in wordSet and pattern not in visited:
# queue.append(curList + [pattern])
# currLayer.add(pattern)
# visited.update(currLayer)
# return res
# if endWord not in wordList:
# return []
# def bfs(beginWord, endWord, patterns):
# graph = defaultdict(set)
# queue = deque([beginWord])
# visited = set([beginWord])
# found = False
# localVisited = set()
# while queue and not found:
# for _ in range(len(queue)):
# word = queue.popleft()
# for i in range(len(word)):
# curPattern = word[:i] + "A*" + word[i + 1:]
# for neighbor in patterns[curPattern]:
# if neighbor == endWord:
# found = True
# if neighbor not in visited:
# localVisited.add(neighbor)
# queue.append(neighbor)
# graph[word].add(neighbor)
# visited.update(localVisited)
# return graph if found else None
# def dfs(word, endWord, graph, path, res):
# path.append(word)
# if word == endWord:
# res.append(list(path))
# else:
# for neighbor in graph[word]:
# dfs(neighbor, endWord, graph, path, res)
# path.pop()
# graph = bfs(beginWord, endWord, patterns)
# if not graph:
# return []
# res = []
# dfs(beginWord, endWord, graph, [], res)
# return res
```
```C++ []
#include <vector>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_map<string, int> depthMap;
vector<vector<string>> ans;
// BFS to find the shortest path
unordered_set<string> wordSet(wordList.begin(), wordList.end());
queue<string> q;
q.push(beginWord);
depthMap[beginWord] = 1;
wordSet.erase(beginWord);
while (!q.empty()) {
string word = q.front();
q.pop();
int steps = depthMap[word];
if (word == endWord) break;
for (int i = 0; i < word.size(); ++i) {
char original = word[i];
for (char ch = 'a'; ch <= 'z'; ++ch) {
word[i] = ch;
if (wordSet.count(word)) {
q.push(word);
wordSet.erase(word);
depthMap[word] = steps + 1;
}
}
word[i] = original;
}
}
// DFS to find all paths
if (depthMap.count(endWord)) {
vector<string> seq = {endWord};
dfs(endWord, beginWord, seq, depthMap, ans);
}
return ans;
}
private:
void dfs(string word, string beginWord, vector<string>& seq, unordered_map<string, int>& depthMap, vector<vector<string>>& ans) {
if (word == beginWord) {
reverse(seq.begin(), seq.end());
ans.push_back(seq);
reverse(seq.begin(), seq.end());
return;
}
int steps = depthMap[word];
for (int i = 0; i < word.size(); ++i) {
char original = word[i];
for (char ch = 'a'; ch <= 'z'; ++ch) {
word[i] = ch;
if (depthMap.count(word) && depthMap[word] + 1 == steps) {
seq.push_back(word);
dfs(word, beginWord, seq, depthMap, ans);
seq.pop_back();
}
}
word[i] = original;
}
}
};
```
```Java []
class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
List<List<String>> ans = new ArrayList<>();
Map<String, Set<String>> reverse = new HashMap<>(); // reverse graph start from endWord
Set<String> wordSet = new HashSet<>(wordList); // remove the duplicate words
wordSet.remove(beginWord); // remove the first word to avoid cycle path
Queue<String> queue = new LinkedList<>(); // store current layer nodes
queue.add(beginWord); // first layer has only beginWord
Set<String> nextLevel = new HashSet<>(); // store nextLayer nodes
boolean findEnd = false; // find endWord flag
while (!queue.isEmpty()) { // traverse current layer nodes
String word = queue.remove();
for (String next : wordSet) {
if (isLadder(word, next)) { // is ladder words
// construct the reverse graph from endWord
Set<String> reverseLadders = reverse.computeIfAbsent(next, k -> new HashSet<>());
reverseLadders.add(word);
if (endWord.equals(next)) {
findEnd = true;
}
nextLevel.add(next); // store next layer nodes
}
}
if (queue.isEmpty()) { // when current layer is all visited
if (findEnd) break; // if find the endWord, then break the while loop
queue.addAll(nextLevel); // add next layer nodes to queue
wordSet.removeAll(nextLevel); // remove all next layer nodes in wordSet
nextLevel.clear();
}
}
if (!findEnd) return ans; // if can't reach endWord from startWord, then return ans.
Set<String> path = new LinkedHashSet<>();
path.add(endWord);
// traverse reverse graph from endWord to beginWord
findPath(endWord, beginWord, reverse, ans, path);
return ans;
}
private void findPath(String endWord, String beginWord, Map<String, Set<String>> graph,
List<List<String>> ans, Set<String> path) {
Set<String> next = graph.get(endWord);
if (next == null) return;
for (String word : next) {
path.add(word);
if (beginWord.equals(word)) {
List<String> shortestPath = new ArrayList<>(path);
Collections.reverse(shortestPath); // reverse words in shortest path
ans.add(shortestPath); // add the shortest path to ans.
} else {
findPath(word, beginWord, graph, ans, path);
}
path.remove(word);
}
}
private boolean isLadder(String s, String t) {
if (s.length() != t.length()) return false;
int diffCount = 0;
int n = s.length();
for (int i = 0; i < n; i++) {
if (s.charAt(i) != t.charAt(i)) diffCount++;
if (diffCount > 1) return false;
}
return diffCount == 1;
}
}
``` | 24 | 0 | ['Hash Table', 'String', 'Backtracking', 'Depth-First Search', 'Breadth-First Search', 'C++', 'Java', 'Python3'] | 4 |
word-ladder-ii | [Python] Accepted BFS Solution with Clean, Commented Code | python-accepted-bfs-solution-with-clean-mzovc | A key observation of this problem is to convert wordList into a graph g = (V, E), where the vertices are all words in wordList and beginWord, and the edges conn | stephenming228 | NORMAL | 2022-08-14T03:55:25.206060+00:00 | 2022-08-14T04:16:59.866589+00:00 | 2,845 | false | A key observation of this problem is to convert `wordList` into a graph g = (V, E), where the vertices are all words in `wordList` and `beginWord`, and the edges connect all words that differ by one character. The graph representation of the example testcase is shown below:\n\n\n\nGiven this graph, we perform a modified BFS traversal to find all shortest paths from start to end words. The psuedo-code for a standard BFS algorithm is:\n\n\nIn this problem, we modify this algorithm as follows. \n\n\t"""\n\tIn a nutshell, this problem is an advanced graph traversal algorithm. Here, we use BFS to find all shortest paths\n\tfrom beginWord to endWord in a constructed graph g = (V, E). \n\t\t- |V| = k+1 if beginWord is not in wordList and |V| = k otherwise.\n\t\t- an edge (u, v) is in E if and only if wordList[u] and wordList[v] differ by exactly one character.\n\tCheck the docstrings for all the necessary methods for an in-depth explanation of this modified BFS algorithm.\n\t"""\n\n\tfrom typing import List\n\timport math\n\t\n\tdef differ(str1, str2):\n\t\t"""\n\t\tdetermines if two strings differ by one character.\n\t\t"""\n\t\tdiff = 0\n\n\t\tfor i in range(len(str1)):\n\t\t\tif str1[i] != str2[i]:\n\t\t\t\tdiff += 1\n\n\t\treturn diff == 1\n\n\n\tdef convert(words):\n\t\t"""\n\t\tconverts words into the adjacency list representation of a graph, as detailed above.\n\t\t"""\n\t\tedges = []\n\t\tgraph = [[] for _ in range(len(words))]\n\n\t\tfor i in range(len(words)):\n\t\t\tfor j in range(i, len(words)):\n\t\t\t\tif differ(words[i], words[j]):\n\t\t\t\t\tedges.append([i, j])\n\n\t\tfor pair in edges:\n\t\t\tgraph[pair[0]].append(pair[1])\n\t\t\tgraph[pair[1]].append(pair[0])\n\n\t\treturn graph\n\n\n\tdef bfs(graph, start):\n\t\t"""\n\t\tperforms a modified bfs search on graph with start node start.\n\n\t\tReturns:\n\t\t\t- parents, a dictionary that maps each node in the graph to a list of parents that have the shortest distance from the start node.\n\n\t\tstart is the index such that wordList[start] = beginWord\n\t\t"""\n\t\tdist = {start: 0} # dictionary that maps each node in graph to the shortest distance away from start.\n\t\tparents = {start: None}\n\n\t\tfor i in range(len(graph)):\n\t\t\tif i != start:\n\t\t\t\tdist[i] = math.inf\n\t\t\t\tparents[i] = []\n\n\t\tqueue = [start]\n\n\t\twhile queue:\n\t\t\tnode = queue.pop()\n\n\t\t\tfor neighbor in graph[node]:\n\t\t\t\tif dist[neighbor] == math.inf: # neighbor has not been visited yet\n\t\t\t\t\tdist[neighbor] = dist[node] + 1\n\t\t\t\t\tparents[neighbor].append(node)\n\t\t\t\t\tqueue.insert(0, neighbor)\n\n\t\t\t\telse: # neighbor has been visited!\n\t\t\t\t\tif dist[node] + 1 == dist[neighbor]:\n\t\t\t\t\t\tparents[neighbor].append(node)\n\t\t\t\t\telif dist[node] + 1 < dist[neighbor]: # found a quicker path to neighbor\n\t\t\t\t\t\tdist[neighbor] = dist[node] + 1\n\t\t\t\t\t\tparents[neighbor].clear()\n\t\t\t\t\t\tparents[neighbor].append(node)\n\n\t\treturn parents\n\n\n\tdef findPaths(pathList, currPath, currNode, parents, wordList):\n\t\t"""\n\t\ttraces back to find all paths from the end node to the start node given the parents dictionary. Returns nothing,\n\t\tbut modifies the input pathList to include all possible paths.\n\t\t"""\n\t\tif parents[currNode] is None:\n\t\t\tcurrPath.reverse()\n\t\t\tpathList.append(currPath)\n\n\t\tif parents[currNode]:\n\t\t\tfor parent in parents[currNode]:\n\t\t\t\tfindPaths(pathList, currPath + [wordList[parent]], parent, parents, wordList)\n\n\n\tclass Solution:\n\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\tif beginWord not in wordList:\n\t\t\t\twordList.append(beginWord)\n\n\t\t\tif endWord not in wordList:\n\t\t\t\treturn []\n\n\t\t\tendIndex = wordList.index(endWord)\n\t\t\tbeginIndex = wordList.index(beginWord)\n\n\t\t\tgraph = convert(wordList)\n\t\t\tparents = bfs(graph, beginIndex)\n\n\t\t\tpathList = []\n\t\t\tcurrPath = [endWord]\n\t\t\tfindPaths(pathList, currPath, endIndex, parents, wordList)\n\n\t\t\treturn pathList\n\n\n\n | 22 | 1 | ['Backtracking', 'Breadth-First Search', 'Graph', 'Python'] | 3 |
word-ladder-ii | [C++] NO TLE, By Using 'int' to Represent the Words. | c-no-tle-by-using-int-to-represent-the-w-sb4z | The Judge of the problem has been updated.\n\n This is a typical BFS problem. We can keep all the paths along with the current nodes, but it will cause TLE.\n\n | n3r0nur12 | NORMAL | 2021-12-12T16:08:57.016617+00:00 | 2022-08-14T19:00:55.438777+00:00 | 2,065 | false | **The Judge of the problem has been updated.**\n\n* This is a typical BFS problem. We can keep all the paths along with the current nodes, but it will cause TLE.\n\n* We can instead keep previous nodes reaching a particular node so that we can traverse back to starting node to get the path.\n\n* But this is not enough. New judge forces us to use ```int``` instead of ```string```.\n\nSo, I had to update my solution. My new solution uses ```int``` values to represent these words.\n\nThe idea is from the user:\n[szlin21](https://leetcode.com/szlin21/)\n\nLet me present the code, step by step.\n```STEP-1:``` Construct the edges between the adjacent nodes.\n```STEP-2:``` Apply BFS by keeping previous nodes reaching the current node.\n```STEP-3:``` Apply DFS to retrieve the paths.\n\n*STEP-1: CONSTRUCT EDGES:*\n```\nint n = size(wordList), src = -1, dst = -1;\nfor (int i = 0; i < n; i++) {\n if (wordList[i] == beginWord) src = i;\n else if (wordList[i] == endWord) dst = i;\n}\nif (dst == -1) return ans;\nif (src == -1) {\n wordList.push_back(beginWord);\n src = n++;\n}\nvector<int> adj[505], parent[505], path = {dst};\nfor (int i = 0; i < n; i++) {\n for (int j = i+1; j < n; j++) {\n if (isAdj(wordList[i], wordList[j])) {\n adj[i].push_back(j);\n adj[j].push_back(i);\n }\n }\n}\n```\n\n*STEP-2: APPLY BFS BY KEEPING PREVIOUS NODES:*\n```\nvoid bfs(vector<int> adj[], vector<int> parent[], int& src) {\n int dist[505] = {};\n fill(begin(dist), end(dist), 505);\n dist[src] = 0;\n queue<int> q;\n q.push(src);\n parent[src] = {-1};\n while (!q.empty()) {\n int v = q.front();\n q.pop();\n for (int u: adj[v]) {\n if (dist[u] > dist[v] + 1) {\n dist[u] = dist[v] + 1;\n q.push(u);\n parent[u] = {v};\n } else if (dist[u] == dist[v] + 1)\n parent[u].push_back(v);\n }\n }\n}\n```\n\n*STEP-3: APPLY DFS TO RETRIEVE PATHS:*\n```\nvoid dfs(vector<string>& wordList, vector<vector<string>>& ans, vector<int> parent[], vector<int>& path, int v) {\n if (v == -1) {\n vector<string> tmp(size(path)-1);\n transform(rbegin(path)+1, rend(path), begin(tmp), [&] (int& t) { return wordList[t]; });\n ans.push_back(move(tmp));\n return;\n }\n for (int u: parent[v]) {\n path.push_back(u);\n dfs(wordList, ans, parent, path, u);\n path.pop_back();\n }\n}\n```\n\n*FULL CODE:*\n```\nclass Solution {\npublic:\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n vector<vector<string>> ans;\n int n = size(wordList), src = -1, dst = -1;\n for (int i = 0; i < n; i++) {\n if (wordList[i] == beginWord) src = i;\n else if (wordList[i] == endWord) dst = i;\n }\n if (dst == -1) return ans;\n if (src == -1) {\n wordList.push_back(beginWord);\n src = n++;\n }\n vector<int> adj[505], parent[505], path = {dst};\n for (int i = 0; i < n; i++) {\n for (int j = i+1; j < n; j++) {\n if (isAdj(wordList[i], wordList[j])) {\n adj[i].push_back(j);\n adj[j].push_back(i);\n }\n }\n }\n bfs(adj, parent, src);\n dfs(wordList, ans, parent, path, dst);\n return ans;\n }\nprivate:\n bool isAdj(string& s1, string& s2) {\n int dif = 0;\n for (int i = 0; i < size(s1); i++)\n dif += s1[i] != s2[i];\n return dif == 1;\n }\n \n void bfs(vector<int> adj[], vector<int> parent[], int& src) {\n int dist[505] = {};\n fill(begin(dist), end(dist), 505);\n dist[src] = 0;\n queue<int> q;\n q.push(src);\n parent[src] = {-1};\n while (!q.empty()) {\n int v = q.front();\n q.pop();\n for (int u: adj[v]) {\n if (dist[u] > dist[v] + 1) {\n dist[u] = dist[v] + 1;\n q.push(u);\n parent[u] = {v};\n } else if (dist[u] == dist[v] + 1)\n parent[u].push_back(v);\n }\n }\n }\n \n void dfs(vector<string>& wordList, vector<vector<string>>& ans, vector<int> parent[], vector<int>& path, int v) {\n if (v == -1) {\n vector<string> tmp(size(path)-1);\n transform(rbegin(path)+1, rend(path), begin(tmp), [&] (int& t) { return wordList[t]; });\n ans.push_back(move(tmp));\n return;\n }\n for (int u: parent[v]) {\n path.push_back(u);\n dfs(wordList, ans, parent, path, u);\n path.pop_back();\n }\n }\n};\n``` | 22 | 0 | ['Breadth-First Search', 'C', 'C++'] | 2 |
word-ladder-ii | Java | BFS | Simple Clear Solution | Algo Explained | 11 ms | java-bfs-simple-clear-solution-algo-expl-zmam | Hit ^Up Vote^ if you like my solution! :)\nPlease comment below if any doubt!\n\n\n/**************************************************************************** | jughead_jr | NORMAL | 2021-05-22T09:11:17.695420+00:00 | 2021-05-22T09:21:30.110694+00:00 | 2,507 | false | **Hit ^Up Vote^ if you like my solution! :)\nPlease comment below if any doubt!**\n\n```\n/********************************************************************************************\n Algo:\n 1. Create a Node Class, which will have 2 param, \n the word as name & path with traverse history.\n\n 2. Load the wordList to set & create a Node Queue for BFS.\n Add the beginWord to the queue.\n \n 3. Iterate the queue level by level.\n\n 4. Each level create a tempRemoveSet, which will track the words getting used.\n And then remove the words from the parent set after every level traversal.\n We are doing this because if we remove while adding it to queue the other possibilites\n shall not come.\n \n 5. While traversing, iterate each node from the queue.\n Check if the current word is the endWord add the path History of the node to the result.\n As, here, we have to find all possiblities we have to keep traversing the all way \n to find all possible paths.\n Next, get the next possible wordList which you can jump from here.\n Iterate through the list add it to the queue.\n Note, here, we are using are passing the current node path history as well \n while creating the node object.\n \n 6. Finally, return the result list.\n \n ********************************************************************************************/\nclass Solution {\n private Set<String> set; // set will congtain the wordList\n private Queue<Node> q; // queue to bfs\n \n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n List<List<String>> result = new ArrayList<>();\n \n set = new HashSet<>();\n q = new LinkedList<>();\n \n for(String s : wordList) set.add(s); //add wordList to set\n \n // if endWord is not in wordList return blank result as no possible path\n if(!set.contains(endWord)) return result; \n \n q.add(new Node(beginWord)); // add the beginNode\n \n while(!q.isEmpty()){\n int size = q.size(); \n // tempset to remove the used word all together after every Iteration\n Set<String> removeSet = new HashSet<>(); \n for(int i=0; i < size; i++){\n Node cur = q.poll();\n if(cur.name.equals(endWord)) {\n result.add(cur.path); // match found add the path history to the result\n }\n else{\n List<String> neighbours = getNeighbours(cur.name);\n for(String n : neighbours){\n q.add(new Node(n, cur.path));\n removeSet.add(n); // add the words getting used, later we will delete all.\n }\n }\n }\n set.removeAll(removeSet); // remove the words used in this traversal\n }\n \n return result;\n }\n \n // generate the possible neighbours to traverse\n private List<String> getNeighbours(String word){\n char[] ch = word.toCharArray();\n List<String> words = new ArrayList<>();\n // replace each char with from a to z\n // and check if thats a valid word\n // if valid add to neighbours list\n for(int i=0; i < ch.length; i++){\n char temp = ch[i];\n for(char j = \'a\'; j <= \'z\'; j++){\n ch[i] = j;\n String newWord = new String(ch);\n if(set.contains(newWord)) words.add(newWord);\n }\n ch[i] = temp;\n }\n return words;\n }\n}\n\n// Node Class to contain the String word & traversal path\nclass Node{\n String name;\n LinkedList<String> path;\n \n // add the string word as name & add it to path as well\n public Node(String name){\n this.name = name;\n this.path = new LinkedList<>();\n this.path.add(name);\n }\n \n // add the name, add path history from parent and then add the current as well.\n public Node(String name, LinkedList<String> path){\n this.name = name;\n this.path = new LinkedList<>();\n this.path.addAll(path);\n this.path.add(name);\n }\n}\n``` | 21 | 1 | ['Breadth-First Search', 'Java'] | 5 |
word-ladder-ii | Python solution | python-solution-by-zitaowang-e9x7 | Idea: First do a BFS on the word graph. The purpose of the BFS is two-fold. First, we calculates the distance from beginWord to all words in wordList. If endWor | zitaowang | NORMAL | 2019-02-22T00:37:44.388642+00:00 | 2019-02-22T00:37:44.388704+00:00 | 2,925 | false | Idea: First do a BFS on the word graph. The purpose of the BFS is two-fold. First, we calculates the distance from `beginWord` to all words in `wordList`. If `endWord` is not in the same connected component as `beginWord`, we `return []`. We store the result in a dictionary `dist`. In particular, we know that the distance `d` from `beginWord` to `endWord` (`dist[endWord]`) is exactly the length of the shortest transformation sequences from `beginWord` to `endWord`. Secondly, we can construct the adjacency list representation of the word graph with the BFS, which is a dictionary `graph` that maps each word to its set of neighbors in the word graph. This facilitates the construction of the shortest transformation sequences using DFS in the next step, because the value corresponding to a particular key will be the set of all the neighbors of the key.\n\nNext, we do a DFS starting from `beginWord`. We can use the dictionary `dist` to prune most of the search spaces, because we already know that each of the shortest transformation sequences is of length `dist[endWord] = d`, so that the transformation sequence is of the form `[beginWord, word1, word2, ..., endWord]`, where `dist[beginWord] = 0`, `dist[word1] = 1`, `dist[word2] = 2`, ..., `dist[endWord] = d`. Therefore, we only need to make recursive DFS calls on those neighbors of the current word which are of distance `dist[currentWord]+1` to the `beginWord`. We initialize two lists, `res` which holds the result, and `tmp` which holds all the words in the current DFS subtree. Once the DFS call is on `endWord`, we create a shallow copy of `tmp` and append it to `res`, and return.\n\n```\nclass Solution(object):\n def findLadders(self, beginWord, endWord, wordList):\n """\n :type beginWord: str\n :type endWord: str\n :type wordList: List[str]\n :rtype: List[List[str]]\n """\n def dfs(word):\n tmp.append(word)\n if word == endWord:\n res.append(list(tmp))\n tmp.pop()\n return \n if word in graph:\n for nei in graph[word]:\n if dist[nei] == dist[word]+1:\n dfs(nei)\n tmp.pop()\n\n wordSet = set(wordList)\n if endWord not in wordSet:\n return []\n alphabets = \'abcdefghijklmnopqrstuvwxyz\'\n q = collections.deque([(beginWord, 0)])\n dist = {}\n graph = collections.defaultdict(set)\n seen = set([beginWord])\n while q:\n u, d = q.popleft()\n dist[u] = d\n for i in range(len(u)):\n for alph in alphabets:\n if alph != u[i]:\n new = u[:i]+alph+u[i+1:]\n if new in wordSet:\n graph[u].add(new)\n graph[new].add(u)\n if new not in seen:\n q.append((new, d+1))\n seen.add(new)\n if endWord not in dist:\n return []\n res = []\n tmp = []\n dfs(beginWord)\n return res \n```\n\nAnother implementation, in which we do the BFS backwards from `endWord` to `beginWord`.\n\n```\nclass Solution(object):\n def findLadders(self, beginWord, endWord, wordList):\n """\n :type beginWord: str\n :type endWord: str\n :type wordList: List[str]\n :rtype: List[List[str]]\n """ \n def dfs(word):\n if word == endWord:\n res.append(list(tmp))\n return\n if word in graph:\n for nei in graph[word]:\n if dist[nei] == dist[word]-1:\n tmp.append(nei)\n dfs(nei)\n tmp.pop()\n \n wordSet = set(wordList)\n if endWord not in wordSet:\n return []\n alphabets = \'abcdefghijklmnopqrstuvwxyz\'\n q = collections.deque([(endWord, 0)])\n min_dist = float(\'inf\')\n seen = set([endWord])\n graph = collections.defaultdict(set)\n dist = {}\n while q:\n u, d = q.popleft()\n dist[u] = d\n for i in range(len(u)):\n for alph in alphabets:\n new = u[:i]+alph+u[i+1:]\n if new == beginWord:\n if min_dist > d+1:\n min_dist = d+1\n graph[beginWord].add(u)\n else: \n if new in wordSet:\n graph[u].add(new)\n graph[new].add(u)\n if new not in seen:\n seen.add(new)\n q.append((new, d+1))\n \n if min_dist == float(\'inf\'):\n return []\n res = []\n tmp = [beginWord]\n for nei in graph[beginWord]:\n if dist[nei] == min_dist-1:\n tmp.append(nei)\n dfs(nei)\n tmp.pop()\n return res\n``` | 21 | 0 | [] | 8 |
word-ladder-ii | My 30ms bidirectional BFS and DFS based Java solution | my-30ms-bidirectional-bfs-and-dfs-based-jwmqe | Regarding speed, 30ms solution beats 100% other java solutions.\n\nCouple of things that make this solution fast:\n\n1) We use Bidirectional BFS which always ex | myfavcat | NORMAL | 2015-11-04T03:56:59+00:00 | 2015-11-04T03:56:59+00:00 | 10,768 | false | Regarding speed, 30ms solution beats 100% other java solutions.\n\nCouple of things that make this solution fast:\n\n1) We use Bidirectional BFS which always expand from direction with less nodes\n\n2) We use char[] to build string so it would be fast \n\n3) Instead of scanning dict each time, we build new string from existing string and check if it is in dict\n\nBelow is my commented code.\n\n public List<List<String>> findLadders(String beginWord, String endWord, Set<String> wordList) {\n //we use bi-directional BFS to find shortest path\n \n Set<String> fwd = new HashSet<String>();\n fwd.add(beginWord);\n \n Set<String> bwd = new HashSet<String>();\n bwd.add(endWord);\n \n Map<String, List<String>> hs = new HashMap<String, List<String>>();\n BFS(fwd, bwd, wordList, false, hs);\n \n List<List<String>> result = new ArrayList<List<String>>();\n \n //if two parts cannot be connected, then return empty list\n if(!isConnected) return result;\n \n //we need to add start node to temp list as there is no other node can get start node\n List<String> temp = new ArrayList<String>();\n temp.add(beginWord);\n \n DFS(result, temp, beginWord, endWord, hs);\n \n return result;\n }\n \n //flag of whether we have connected two parts\n boolean isConnected = false;\n \n public void BFS(Set<String> forward, Set<String> backward, Set<String> dict, boolean swap, Map<String, List<String>> hs){\n \n //boundary check\n if(forward.isEmpty() || backward.isEmpty()){\n return;\n }\n \n //we always do BFS on direction with less nodes\n //here we assume forward set has less nodes, if not, we swap them\n if(forward.size() > backward.size()){\n BFS(backward, forward, dict, !swap, hs);\n return;\n }\n \n //remove all forward/backward words from dict to avoid duplicate addition\n dict.removeAll(forward);\n dict.removeAll(backward);\n \n //new set contains all new nodes from forward set\n Set<String> set3 = new HashSet<String>();\n \n //do BFS on every node of forward direction\n for(String str : forward){\n //try to change each char of str\n for(int i = 0; i < str.length(); i++){\n //try to replace current char with every chars from a to z \n char[] ary = str.toCharArray();\n for(char j = 'a'; j <= 'z'; j++){\n ary[i] = j;\n String temp = new String(ary);\n \n //we skip this string if it is not in dict nor in backward\n if(!backward.contains(temp) && !dict.contains(temp)){\n continue;\n }\n \n //we follow forward direction \n String key = !swap? str : temp;\n String val = !swap? temp : str;\n\n if(!hs.containsKey(key)) hs.put(key, new ArrayList<String>());\n \n //if temp string is in backward set, then it will connect two parts\n if(backward.contains(temp)){\n hs.get(key).add(val);\n isConnected = true;\n }\n \n //if temp is in dict, then we can add it to set3 as new nodes in next layer\n if(!isConnected && dict.contains(temp)){\n hs.get(key).add(val);\n set3.add(temp);\n }\n }\n \n }\n }\n \n //to force our path to be shortest, we will not do BFS if we have found shortest path(isConnected = true)\n if(!isConnected){\n BFS(set3, backward, dict, swap, hs);\n }\n }\n \n public void DFS(List<List<String>> result, List<String> temp, String start, String end, Map<String, List<String>> hs){\n //we will use DFS, more specifically backtracking to build paths\n \n //boundary case\n if(start.equals(end)){\n result.add(new ArrayList<String>(temp));\n return;\n }\n \n //not each node in hs is valid node in shortest path, if we found current node does not have children node,\n //then it means it is not in shortest path\n if(!hs.containsKey(start)){\n return;\n }\n \n for(String s : hs.get(start)){\n temp.add(s);\n DFS(result, temp, s, end, hs);\n temp.remove(temp.size()-1);\n \n }\n }\n\n\nThe main idea is from [awesome solution][1]\n\n\n [1]: https://leetcode.com/discuss/44110/super-fast-java-solution-two-end-bfs | 20 | 0 | ['Depth-First Search', 'Breadth-First Search'] | 2 |
word-ladder-ii | C++ BFS + DFS | c-bfs-dfs-by-jianchao-li-v2te | After reading some solutions, I wrote the following one, which was mainly inspired by this one. The difference is that the previous solution maps children to pa | jianchao-li | NORMAL | 2019-02-22T11:09:59.823186+00:00 | 2019-02-22T11:09:59.823246+00:00 | 4,938 | false | After reading some solutions, I wrote the following one, which was mainly inspired by [this one](https://leetcode.com/problems/word-ladder-ii/discuss/40594/A-concise-solution-using-bfs-and-backtracing). The difference is that the previous solution maps children to parents while I map from parents to children (this makes the DFS more natural). The idea is to first use BFS to search from `beginWord` to `endWord` and generate the word-to-children mapping at the same time. Then, use DFS (backtracking) to generate the transformation sequences according to the mapping.\n\n```cpp\nclass Solution {\npublic:\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n unordered_set<string> dict(wordList.begin(), wordList.end()), current, next;\n if (dict.find(endWord) == dict.end()) {\n return {};\n }\n unordered_map<string, vector<string>> children;\n vector<vector<string>> ladders;\n vector<string> ladder;\n current.insert(beginWord);\n ladder.push_back(beginWord);\n while (true) {\n for (string word : current) {\n dict.erase(word);\n }\n for (string word : current) {\n findChildren(word, next, dict, children);\n }\n if (next.empty()) {\n break;\n }\n if (next.find(endWord) != next.end()) {\n genLadders(beginWord, endWord, children, ladder, ladders);\n break;\n }\n current.clear();\n swap(current, next);\n }\n return ladders;\n }\nprivate:\n\n void findChildren(string word, unordered_set<string>& next, unordered_set<string>& dict, unordered_map<string, vector<string>>& children) {\n string parent = word;\n for (int i = 0; i < word.size(); i++) {\n char t = word[i];\n for (int j = 0; j < 26; j++) {\n word[i] = \'a\' + j;\n if (dict.find(word) != dict.end()) {\n next.insert(word);\n children[parent].push_back(word);\n }\n }\n word[i] = t;\n }\n }\n\n void genLadders(string beginWord, string endWord, unordered_map<string, vector<string>>& children, vector<string>& ladder, vector<vector<string>>& ladders) {\n if (beginWord == endWord) {\n ladders.push_back(ladder);\n } else {\n for (string child : children[beginWord]) {\n ladder.push_back(child);\n genLadders(child, endWord, children, ladder, ladders);\n ladder.pop_back();\n }\n }\n }\n};\n```\n\nThe codes can also be written in a graph-theoretic manner.\n\n```cpp\nclass Solution {\npublic:\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n unordered_set<string> dict(wordList.begin(), wordList.end());\n if (dict.find(endWord) == dict.end()) {\n return {};\n }\n graph g;\n vector<vector<string>> paths;\n vector<string> path = {beginWord};\n if (buildGraph(g, beginWord, endWord, dict)) {\n findPaths(g, beginWord, endWord, path, paths);\n }\n return paths;\n }\nprivate:\n typedef unordered_map<string, vector<string>> graph;\n \n bool buildGraph(graph& g, string beginWord, string endWord, unordered_set<string>& dict) {\n unordered_set<string> todo;\n todo.insert(beginWord);\n while (!todo.empty()) {\n if (todo.find(endWord) != todo.end()) {\n return true;\n }\n for (string word : todo) {\n dict.erase(word);\n }\n unordered_set<string> temp;\n for (string word : todo) {\n string parent = word;\n for (int i = 0; i < word.size(); i++) {\n char c = word[i];\n for (int j = 0; j < 26; j++) {\n word[i] = \'a\' + j;\n if (dict.find(word) != dict.end()) {\n temp.insert(word);\n g[parent].push_back(word);\n }\n }\n word[i] = c;\n }\n }\n swap(todo, temp);\n }\n return false;\n }\n \n void findPaths(graph& g, string beginWord, string endWord, vector<string>& path, vector<vector<string>>& paths) {\n if (beginWord == endWord) {\n paths.push_back(path);\n } else {\n for (string child : g[beginWord]) {\n path.push_back(child);\n findPaths(g, child, endWord, path, paths);\n path.pop_back();\n }\n }\n }\n};\n``` | 19 | 0 | ['Backtracking', 'Depth-First Search', 'Breadth-First Search', 'C++'] | 4 |
word-ladder-ii | Share my 130 ms Python solution | share-my-130-ms-python-solution-by-dashe-5ovt | Main idea:\n\n1. Use character flipping\n\n2. Two-end BFS\n\n3. defaultdict(list) for easy writing to keep track of paths\n\nI also use set intersection to dete | dasheng2 | NORMAL | 2015-07-27T09:03:56+00:00 | 2015-07-27T09:03:56+00:00 | 5,986 | false | Main idea:\n\n1. Use character flipping\n\n2. Two-end BFS\n\n3. defaultdict(list) for easy writing to keep track of paths\n\nI also use set intersection to determine if we are done\n\n from collections import defaultdict\n class Solution:\n # @param start, a string\n # @param end, a string\n # @param dict, a set of string\n # @return a list of lists of string\n def findLadders(self, start, end, dict):\n wordLen = len(start)\n front, back = defaultdict(list), defaultdict(list)\n front[start].append([start])\n back[end].append([end])\n # remove start from dict, add end to dict if it is not there\n dict.discard(start)\n if end not in dict:\n dict.add(end)\n forward, result = True, []\n while front:\n # get all valid transformations\n nextSet = defaultdict(list)\n for word, paths in front.items():\n for index in range(wordLen):\n for ch in 'abcdefghijklmnopqrstuvwxyz':\n nextWord = word[:index] + ch + word[index+1:]\n if nextWord in dict:\n # update paths\n if forward:\n # append next word to path\n nextSet[nextWord].extend([path + [nextWord] for path in paths])\n else:\n # add next word in front of path\n nextSet[nextWord].extend([[nextWord] + path for path in paths])\n front = nextSet\n common = set(front) & set(back)\n if common:\n # path is through\n if not forward:\n # switch front and back if we were searching backward\n front, back = back, front\n result.extend([head + tail[1:] for word in common for head in front[word] for tail in back[word]])\n return result\n \n if len(front) > len(back):\n # swap front and back for better performance (smaller nextSet)\n front, back, forward = back, front, not forward\n \n # remove transformations from wordDict to avoid cycles\n dict -= set(front)\n \n return [] | 17 | 1 | ['Python'] | 3 |
word-ladder-ii | Java Solution with Iteration | java-solution-with-iteration-by-alextheg-g7bp | Code is about 40 lines, put explanation in comments.\n\n /*\n * we are essentially building a graph, from start, BF.\n * and at each level we find al | alexthegreat | NORMAL | 2015-01-15T18:28:57+00:00 | 2015-01-15T18:28:57+00:00 | 7,738 | false | Code is about 40 lines, put explanation in comments.\n\n /**\n * we are essentially building a graph, from start, BF.\n * and at each level we find all reachable words from parent.\n * we stop if the current level contains end,\n * we return any path whose last node is end.\n * \n * to achieve BFT, use a deuqe;\n * a key improvement is to remove all the words we already reached\n * in PREVIOUS LEVEL; we don't need to try visit them again\n * in subsequent level, that is guaranteed to be non-optimal solution.\n * at each new level, we will removeAll() words reached in previous level from dict.\n */\n public List<List<String>> findLadders(String start, String end, Set<String> dict) {\n List<List<String>> results = new ArrayList<List<String>>();\n dict.add(end);\n // instead of storing words we are at, we store the paths.\n Deque<List<String>> paths = new LinkedList<List<String>>();\n List<String> path0 = new LinkedList<String>();\n path0.add(start);\n paths.add(path0);\n // if we found a path ending at 'end', we will set lastLevel,\n // use this data to stop iterating further.\n int level = 1, lastLevel = Integer.MAX_VALUE;\n Set<String> wordsPerLevel = new HashSet<String>();\n while (!paths.isEmpty()) {\n List<String> path = paths.pollFirst();\n if (path.size() > level) {\n dict.removeAll(wordsPerLevel);\n wordsPerLevel.clear();\n level = path.size();\n if (level > lastLevel)\n break; // stop and return\n }\n // try to find next word to reach, continuing from the path\n String last = path.get(level - 1);\n char[] chars = last.toCharArray();\n for (int index = 0; index < last.length(); index++) {\n char original = chars[index];\n for (char c = 'a'; c <= 'z'; c++) {\n chars[index] = c;\n String next = new String(chars);\n if (dict.contains(next)) {\n wordsPerLevel.add(next);\n List<String> nextPath = new LinkedList<String>(path);\n nextPath.add(next);\n if (next.equals(end)) {\n results.add(nextPath);\n lastLevel = level; // curr level is the last level\n } else\n paths.addLast(nextPath);\n }\n }\n chars[index] = original;\n }\n }\n \n return results;\n } | 17 | 0 | [] | 4 |
word-ladder-ii | [Python3] Easy Solution, Detailed Explanation | python3-easy-solution-detailed-explanati-i77i | 1. Understanding the problem\n1. there is a starting word, beginWord and an ending word, endWord.\n2. there are a bunch of words in between, following the const | chaudhary1337 | NORMAL | 2021-07-24T10:59:13.458249+00:00 | 2021-07-25T16:13:50.583874+00:00 | 2,666 | false | ## 1. Understanding the problem\n1. there is a starting word, `beginWord` and an ending word, `endWord`.\n2. there are a bunch of words in between, following the constrataint that they can\'t have more than one character different between them.\n3. the "bunch of words" are taken from the `wordList` given.\n4. Goal: find the *shortest* **paths** from `beginWord` to `endWord`.\n\nExample explaination (as taken from question):\n```\nInput: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]\nOutput: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]\nExplanation: There are 2 shortest transformation sequences:\n"hit" -> "hot" -> "dot" -> "dog" -> "cog"\n"hit" -> "hot" -> "lot" -> "log" -> "cog"\n```\n\nBetween \'hit\' and \'hot\' there is a single character difference, from \'i\' to \'o\'. Similarly for \'dot\' and \'dog\' and then \'dog\' and \'cog\'. We can\'t jump the difference in characters - which has to be 1.\n\n## 2. Naive Approach\nWe start from `beginWord`. There are lots of variations that can *spawn* from it. Let\'s say the word is \'cat\'. The variations can be \'\\*at\' or \'c\\*t\' or \'ca\\*\', with \'\\*\' itself being an alphabet, of one of 26. That\'s `len(word)*26` variants.\n\nWe thus simply need to enumerate all possibilites at all the given steps, keeping the one character change constraint in mind - and *some* of them may reach the desired word, `endWord`. Note that all the possiblities are *not* actually needed because we have a restriction from the list `wordList`.\n\nHow can enumerate all the paths? **queue**.\nHere\'s a proof of concept:\n```\nput the `beginWord` in the queue. \nwhile the queue is non empty\n extract the first element in queue\n if it is, we have an answer!\n check if its the ending element\n find all the *valid* variants of the word\n append all those variants in the queue \n```\n\n## 3. Notes\n- We need to store paths, to return as the answer and not the elements\n- Yes, those mean a lot of copies :P\n- We remove the word we have already seen in the queue, from the list. Why? This prevents words already accounted-for, coming back in the queue (to infinity!)\n\n## 4. Solution\n```\nimport queue\n\nclass Solution:\n # returns True if w and word are only one character apart\n # else returns False\n def valid(self, w, word):\n diff = 0\n for (x, y) in zip(w, word):\n if x != y: diff += 1\n\n return True if diff <= 1 else False\n \n # returns the neighbours\n # I kept the name as friends because \n # I always have to google the spelling of neighbours\n def get_friends(self, word):\n return [w for w in self.wordList if self.valid(w, word)]\n\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n self.wordList = wordList\n q = queue.Queue()\n ans = []\n # keeping the paths instead of the words in the queue\n q.put([beginWord]) \n \n while not q.empty():\n path = q.get()\n word = path[-1]\n if word in self.wordList: self.wordList.remove(word)\n\n if word == endWord:\n # the below looks scary, but is trivial\n # We are just trying to see if the path is the\n # *smallest* possible or not\n if (len(ans) and len(path) <= len(ans[-1])) or not len(ans):\n ans.append(path)\n \n # adding new elements in the list\n for w in self.get_friends(word):\n q.put(path.copy()+[w])\n\n return ans\n```\n\n## 5. Improving & Optimizing\nIf you run the above, the space and time complexities are ... sad. Here\'s one way to make them better. Recall how we are always calling the `self.get_friends(word)` function again and again? What if the same word comes up again and again? We should have a data structure that stores whoose friends are who - and, who all friends we have seen already (`self.wordList` won\'t cut it. Think Why!)\n\nThe last function is changed, the helper functions remain the same.\n```\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n self.wordList = wordList+[beginWord] # NOTE this change!\n q = queue.Queue()\n ans = []\n q.put([beginWord])\n \n # storing whoose friend is who, at the very start itself\n d = {}\n for word in self.wordList:\n d[word] = self.get_friends(word) # same as before\n # storing who all we have already accounted for\n seen = set()\n \n while not q.empty():\n path = q.get()\n word = path[-1]\n seen.add(word)\n \n if word == endWord: \n\t\t\t\t# thanks to https://leetcode.com/ngzza/ for simpler and cleaner line of code\n if not ans or len(path) <= len(ans[-1]:\n ans.append(path)\n \n for w in d[word]:\n # the check, which replaces the self.wordList check\n # since the wordList check won\'t work\n if w not in seen:\n q.put(path.copy()+[w])\n \n \n return ans\n```\n\nAny and all comments/constructive criticisms are very welcome! | 16 | 3 | ['Queue', 'Python', 'Python3'] | 3 |
word-ladder-ii | [Python3] Word Ladder II: Simple BFS | python3-word-ladder-ii-simple-bfs-by-man-7y6v | \ndef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n graph = collections.defaultdict(set)\n l = len(wo | phoenix-2 | NORMAL | 2020-11-13T06:47:25.305640+00:00 | 2020-11-13T06:47:25.305673+00:00 | 2,052 | false | ```\ndef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n graph = collections.defaultdict(set)\n l = len(wordList[0])\n\n wordList = set(wordList)\n if endWord not in wordList:\n return []\n\n wordList.add(beginWord)\n\n def get_matches(word):\n return {word[:i]+\'*\'+word[i+1:] for i in range(l)}\n\n for word in wordList:\n matches = get_matches(word)\n for match in matches:\n graph[match].add(word)\n graph[word] = matches\n\n ans = []\n min_path = None\n seen = set()\n\n q = collections.deque([(beginWord, 1, [beginWord])])\n\n while q:\n word, length, seq = q.popleft()\n\n for w in graph[word]:\n if w == endWord and (not min_path or min_path == length+1):\n min_path = length+1\n seq.extend([w])\n ans.append(seq)\n \n if w not in seen: \n if w in wordList:\n q.append((w, length, seq+[w]))\n else:\n q.append((w, length+1, seq))\n seen.add(word)\n\n return ans\n\n``` | 16 | 0 | ['Breadth-First Search', 'Python3'] | 3 |
word-ladder-ii | O(n * w) TIme and O(n^2 * w) Space Complexity, TLE and MLE Optimized!!! | on-w-time-and-on2-w-space-complexity-tle-ferh | Intuition\nFrom the problem statement, we had an idea of applying a BFS or DFS starting from beginWord and terminating at endWord. Later we also know that in th | sahityakmr | NORMAL | 2023-10-23T17:43:32.719945+00:00 | 2023-10-23T17:43:32.719969+00:00 | 626 | false | # Intuition\nFrom the problem statement, we had an idea of applying a BFS or DFS starting from beginWord and terminating at endWord. Later we also know that in this search, we\'ll have to pick the paths with minimum length. Also, to note that, there may be multiple ways to reach a particular intermediate/terminal word, so the flow is not exactly how we traverse a tree.\n\n# Approach\nThe approach would be to create a BFS layers, the first layer would contain the begin word, the next layer would contain the words which were generated post modifying the current layer (basically replacing one character). At each layer we are storing the parent\'s reference in a dict(set) as word:(reachable_from...). \nLater doing a dfs search from endWord to beginWord will give the flow\nto create the result array.\n\n# Complexity\n- Time complexity:\nO(n * w) # we are traversing each word once\n\n- Space complexity:\nO(n^2 * w) # we are storing the parent mapping\n\n# Code\n```\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n wordList = set(wordList) # converting the given list to set to perform optimized set reduction\n result = []\n layer = set()\n layer.add(beginWord) # maintaining each layer to do bfs for the next layer\n # a dictionary to maintain the parent of each word, note in this bfs, one node can have multiple parent\n # e.g.: we can arrive at \'cog\' from \'dog\' and \'log\'\n # this parent chaining will help us save some memory and create the required list later using build_path\n parent = defaultdict(set)\n while layer:\n new_layer = set()\n for word in layer:\n for i in range(len(beginWord)):\n for c in "abcdefghijklmnopqrstuvwxyz":\n new = word[:i] + c + word[i + 1:]\n if new in wordList and new != word:\n parent[new].add(word)\n new_layer.add(new)\n wordList -= new_layer\n layer = new_layer\n\n def build_path(last, lst):\n if last == beginWord:\n result.append(list(reversed(lst))) # since we build the path bottom up, so reversing\n return\n for word in parent[last]:\n build_path(word, lst + [word])\n\n build_path(endWord, [endWord])\n return result\n``` | 15 | 0 | ['Python3'] | 2 |
word-ladder-ii | Java Solution | 88 ms | java-solution-88-ms-by-adarsh-mishra27-jv9v | \nclass Solution {\n public List<List<String>> ans;\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n | adarsh-mishra27 | NORMAL | 2022-08-14T17:07:18.586524+00:00 | 2022-08-14T17:07:18.586554+00:00 | 2,197 | false | ```\nclass Solution {\n public List<List<String>> ans;\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n ans=new ArrayList<>();\n \n Map<String, List<String>> graph = new HashMap<>();\n for(String s: wordList) {\n graph.put(s, new ArrayList<>());\n }\n //if beginword is not in graph then add it\n if(!graph.containsKey(beginWord)) {\n wordList.add(beginWord);\n graph.put(beginWord, new ArrayList<>());\n }\n \n for(String s: wordList) {\n for(int i=0;i<s.length();i++) {\n for(char ch=\'a\';ch<=\'z\';ch++) {\n String checkWord=s.substring(0, i)+ch+s.substring(i+1);\n if(graph.containsKey(checkWord) && !s.equals(checkWord)) {\n List<String> l=graph.get(s);\n l.add(checkWord);\n graph.put(s, l);\n }\n }\n }\n }\n \n Set<String> visited=new HashSet<>(wordList.size());\n Map<String, Integer> distFromStarting = new HashMap<>(); //distance from begin node\n //will use it to calculate dfs in reverse order from endWord to beginWord\n \n //debug\n // System.out.println("Graph->"+graph);\n \n int shortestLength = bfs(beginWord, endWord, graph, visited, distFromStarting); //for shortest path using bfs\n if(shortestLength==0) return ans;\n \n //debug\n // System.out.println(distFromStarting);\n \n //optimised DFS\n reverseDFS(endWord, beginWord, new ArrayList<>(), graph, distFromStarting);\n return ans;\n }\n \n //from source to destination bfs\n public int bfs(String src, String des, Map<String, List<String>> graph, Set<String> visited, Map<String, Integer> distFromStarting) {\n List<List<String>> ans=new ArrayList<>();\n \n Queue<String> queue=new LinkedList<>();\n queue.add(src);\n visited.add(src);\n int level=0;\n distFromStarting.put(src, 0);\n \n while(!queue.isEmpty()) {\n int size=queue.size();\n \n for(int i=0;i<size;i++) {\n String cur=queue.remove();\n //debug\n // System.out.println(ret);\n if(cur.equals(des)) {\n return level;\n }\n for(String n: graph.get(cur)) {\n if(!visited.contains(n)) {\n visited.add(n);\n queue.add(n);\n distFromStarting.put(n, distFromStarting.get(cur)+1);\n }\n }\n }\n \n level++;\n }\n //debug\n // System.out.println(ret);\n return 0;\n }\n \n public void reverseDFS(String src, String des, List<String> path, Map<String, List<String>> graph, Map<String , Integer> distFromStarting) {\n if(src.equals(des)) {\n path.add(des);\n List<String> list=new ArrayList<>(path);\n Collections.reverse(list);\n \n //debug\n // System.out.println(list);\n \n ans.add(list);\n path.remove(path.size()-1);\n return;\n }\n \n path.add(src);\n \n //debug\n // System.out.println(path);\n \n for(String next: graph.get(src)) {\n // System.out.println(path+" "+next);\n if(distFromStarting.containsKey(next) && distFromStarting.get(next)+1==distFromStarting.get(src)) {\n reverseDFS(next, des, path, graph, distFromStarting);\n }\n }\n \n path.remove(path.size()-1);\n }\n}\n``` | 14 | 0 | ['Backtracking', 'Depth-First Search', 'Breadth-First Search', 'Java'] | 3 |
word-ladder-ii | A concise solution using bfs and backtracing | a-concise-solution-using-bfs-and-backtra-1l7n | the basic idea is referred from url: http://yucoding.blogspot.com/2014/01/leetcode-question-word-ladder-ii.html\n \n unordered_map > mp; // a map indicati | shichaotan | NORMAL | 2015-02-01T01:22:07+00:00 | 2015-02-01T01:22:07+00:00 | 7,706 | false | the basic idea is referred from url: http://yucoding.blogspot.com/2014/01/leetcode-question-word-ladder-ii.html\n \n unordered_map<string, vector<string> > mp; // a map indicating a word's previous word list\n vector<vector<string> > res;\n vector<string> path;\n \n void output(string &start, string last) {\n if (last == start) {\n // vector<string> t(path.rbegin(), path.rend());\n // res.push_back(t);\n reverse(path.begin(), path.end());\n res.push_back(path);\n reverse(path.begin(), path.end());\n }\n else {\n // backtracing to get path recursively\n for (int i = 0; i < mp[last].size(); ++i) {\n path.push_back(mp[last][i]);\n output(start, mp[last][i]);\n path.pop_back();\n }\n }\n }\n \n void findNext(string str, unordered_set<string> &dict, unordered_set<string> &next_lev) {\n for (int i = 0; i < str.size(); ++i) {\n string s = str;\n for (char j = 'a'; j <= 'z'; ++j) {\n s[i] = j;\n if (dict.count(s)) {\n next_lev.insert(s);\n mp[s].push_back(str);\n }\n }\n }\n }\n \n vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) {\n unordered_set<string> cur_lev;\n cur_lev.insert(start);\n unordered_set<string> next_lev;\n path.push_back(end);\n \n // expand to get all the next level valid words\n while (true) {\n for (auto it = cur_lev.begin(); it != cur_lev.end(); it++)\n dict.erase(*it); //delete previous level words from dict to avoid the cycle\n \n for (auto it = cur_lev.begin(); it != cur_lev.end(); it++)\n findNext(*it, dict, next_lev); //find current level words\n \n if (next_lev.empty()) return res;\n \n if (next_lev.count(end)) { //if find end string\n output(start, end);\n return res;\n }\n \n cur_lev = next_lev;\n next_lev.clear();\n }\n \n return res; \n } | 14 | 1 | [] | 4 |
word-ladder-ii | Java Efficient Solution✅Updated ✅ | java-efficient-solutionupdated-by-vaibha-prb7 | \n\nclass Solution {\n Set<String> set = new HashSet();\n String beginWord, endWord;\n Map<String, Integer> dist = new HashMap();\n List<List<String | vaibhavnirmal2001 | NORMAL | 2022-08-14T13:55:30.811305+00:00 | 2022-08-14T13:55:30.811349+00:00 | 2,374 | false | \n```\nclass Solution {\n Set<String> set = new HashSet();\n String beginWord, endWord;\n Map<String, Integer> dist = new HashMap();\n List<List<String>> res;\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n this.beginWord = beginWord;\n this.endWord = endWord;\n this.res = new ArrayList();\n for (String word : wordList) {\n set.add(word);\n }\n short_path();\n if (dist.get(endWord) == null) return res;\n List<String> path = new ArrayList();\n path.add(endWord);\n dfs(endWord, path);\n return res;\n }\n \n private void short_path() {\n Queue<String> q = new LinkedList();\n q.offer(beginWord);\n dist.put(beginWord, 0);\n while(q.size() > 0) {\n String cur = q.poll();\n if (cur.equals(endWord) ) break;\n char[] charCur = cur.toCharArray();\n for (int i = 0; i < cur.length(); i++) {\n char c = charCur[i];\n for (char j = \'a\'; j <= \'z\'; j++) {\n charCur[i] = j;\n String s = new String(charCur);\n if (set.contains(s) && dist.get(s) == null) {\n dist.put(s, dist.get(cur) + 1);\n q.offer(s);\n }\n \n }\n charCur[i] = c;\n }\n }\n }\n \n private void dfs(String word, List<String> path) {\n if (word.equals(beginWord)) {\n List list = new ArrayList(path);\n Collections.reverse(list);\n res.add(list);\n return;\n }\n char[] charCur = word.toCharArray();\n for (int i = 0; i < word.length(); i++) {\n char c = charCur[i];\n for (char j = \'a\'; j <= \'z\'; j++) {\n charCur[i] = j;\n String s = new String(charCur);\n if (dist.get(s) != null && dist.get(s) + 1 == dist.get(word)) {\n path.add(s);\n dfs(s, path);\n path.remove(path.size() - 1);\n }\n \n }\n charCur[i] = c;\n }\n }\n}\n``` | 13 | 0 | ['Java'] | 3 |
word-ladder-ii | [Java] Clean BFS + DFS Solution (98% Two-Way BFS) || with comments | java-clean-bfs-dfs-solution-98-two-way-b-xd5o | Before trying this question, make sure to totally digest this question: \n 127. Word Ladder\n\nAlso, it will be nice to \n1. know how to analyze the Time & Spac | xieyun95 | NORMAL | 2021-05-16T05:47:24.558243+00:00 | 2021-05-16T06:54:34.411510+00:00 | 1,410 | false | Before trying this question, make sure to totally digest this question: \n* [127. Word Ladder](https://leetcode.com/problems/word-ladder/discuss/1210829/Java-clean-Two-Way-BFS-Solution-oror-with-Analysis)\n\nAlso, it will be nice to \n1. know how to analyze the Time & Space Complexity of the algorithm. \n2. understand why and how to use Two-Way BFS \n\nNotice when building parentsMap, we start from the endword. We construct the map as follows: \n``` \n// Graph\n c -> d\n /\nstartWord -> a -> b -> endWord\n \\ / /\n e -> f \n// parentsMap: \n\t\tb : {endWord}\n\t\tf : {endWord}\n\t\ta : {b}\n\t\te : {b, f}\nstartWord : {a, e}\n```\nNotice we do not traverse those words that\n1. starting from startWord\n2. not on any shortest path \n\nThus when we perform DFS from the startWord, every step we move is on a valid shortest path. \n\n**Analysis of the Time & Space Complexity**\n\n1. the Complexity of **findNeighbors()**\n```\n// denote M := length of each word\n// N := length of wordList(number of words of input)\nTime Complexity: O(M^ 2)\n\t\tM (iterate through the whole word by each char) *\n\t\t26 (26 choices of changing each char) *\n\t\tM (creating a new String) *\n\t O(1) (check existance in the HashSet) \n\t\t\nSpace Complexity: O(min(M* N , 26 ^ M))\n M * N list of results at most has N words (all words), each has M chars\n\t 26 ^ M each char has 26 choices \n```\n2. the Complexity of **buildMap()**\n```\nTime Complexity: O(N * M^ 2)\n\t\tN (each word at most once) * \n\t O(M^2) (helper-function findNeighbors()) \n \nSpace Complexity: O(N^ 2 * M)\n O(min(M* N , 26 ^ M)) (helper-function findNeighbors())\n\t O(N ^ 2 * M) consider the following cases\n\t \nstartWord -> S_1 -> S_2 ... -> S_1 -> endWord\nstartWord -> {words with dist == 1} -> {words with dist == 2} ... -> {words with dist == k} -> endWord\n\t\t\t\t\tsize = N / k size = N / k size = N / k \nConsider middle sets S_i & S_(i+1), if every word in S_i may lead to every word in S_(i+1); \nThen the total Space Complexity is :\n\t\tN / k (number of keys in each layer: ) *\n\t\tN / k (number of descendants of each key) *\n\t\t M (length of each word) *\n\t\t k (total layers)\nThus we may need O(N^2 * M)-Space.\n```\n\n**Solution (One-Way BFS + DFS):** \n\n```\nclass Solution {\n private Set<String> dict;\n private String beginWord;\n private String endWord;\n \n private Map<String, List<String>> parentsMap = new HashMap<>();\n private List<List<String>> paths = new ArrayList<>();\n \n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n this.dict = new HashSet(wordList);\n dict.add(beginWord);\n \n if (!dict.contains(endWord)) return paths;\n this.beginWord = beginWord;\n this.endWord = endWord;\n \n if (!buildMap()) return paths;\n \n List<String> curr = new ArrayList<>();\n curr.add(beginWord);\n \n collectAllPaths(beginWord, curr);\n \n return paths;\n }\n \n private void collectAllPaths(String s, List<String> curr) {\n if (s.equals(endWord)) {\n paths.add(new ArrayList(curr));\n return;\n }\n \n for (String next : parentsMap.get(s)) {\n curr.add(next);\n collectAllPaths(next, curr);\n curr.remove(curr.size() - 1);\n }\n }\n \n \n private boolean buildMap() {\n Set<String> backward = new HashSet<>();\n backward.add(endWord);\n \n Set<String> visited = new HashSet<>();\n boolean found = false;\n \n while (!backward.isEmpty() && !found) {\n Set<String> temp = new HashSet<>();\n \n for (String s : backward) {\n visited.add(s);\n \n for (String nb : getNext(s)) {\n \n if (backward.contains(nb) || visited.contains(nb)) continue;\n if (beginWord.equals(nb)) found = true;\n\n temp.add(nb);\n parentsMap.putIfAbsent(nb, new ArrayList<>());\n parentsMap.get(nb).add(s);\n }\n }\n backward = temp;\n }\n return found;\n }\n \n private List<String> getNext(String s) {\n char[] arr = s.toCharArray();\n List<String> nbs = new ArrayList<>();\n \n for (int i = 0; i < arr.length; i++) {\n char ch = arr[i];\n for (char c = \'a\'; c <= \'z\'; c++) {\n if (c == ch) continue;\n arr[i] = c;\n String nb = new String(arr);\n if (dict.contains(nb)) nbs.add(nb);\n }\n arr[i] = ch;\n }\n \n return nbs;\n }\n}\n```\n\nIf you are still interested, we may optimize this using Two-Way BFS. The code is maybe too long for an interview session though: \n\n**Solution (Two-Way BFS + DFS):** \n```\nclass Solution {\n private Set<String> dict;\n private String beginWord;\n private String endWord;\n \n // Key: String Value: parents in the sense that close to beginWord/endWord;\n private Map<String, List<String>> forwardMap = new HashMap<>(); \n private Map<String, List<String>> backwardMap = new HashMap<>(); \n \n // Key: String (always appears in a path) Value: list of String that could be the next String in some paths\n private Map<String, List<String>> pathMap = new HashMap<>();\n \n private Set<String> intersect;\n \n private List<List<String>> paths = new ArrayList<>();\n \n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n this.dict = new HashSet(wordList);\n if (!dict.contains(endWord)) return paths;\n \n this.beginWord = beginWord;\n this.endWord = endWord;\n \n this.intersect = buildMaps();\n if (intersect.size() == 0) return paths;\n \n trimForwardMap();\n trimBackwardMap();\n \n List<String> curr = new ArrayList<>();\n curr.add(beginWord);\n collectAllPaths(beginWord, curr);\n \n return paths;\n }\n \n private void collectAllPaths(String s, List<String> curr) {\n if (s.equals(endWord)) {\n paths.add(new ArrayList(curr));\n return;\n }\n \n for (String next : pathMap.get(s)) {\n curr.add(next);\n collectAllPaths(next, curr);\n curr.remove(curr.size() - 1);\n }\n \n }\n \n \n private Set<String> buildMaps() {\n Set<String> forward = new HashSet<>();\n forward.add(beginWord);\n \n Set<String> backward = new HashSet<>();\n backward.add(endWord);\n \n Set<String> visited = new HashSet<>();\n Set<String> intersect = new HashSet<>();\n \n boolean found = false;\n boolean reverse = false; \n \n \n while(!forward.isEmpty() && !found) {\n if (forward.size() > backward.size()) {\n Set<String> temp = forward;\n forward = backward;\n backward = temp;\n reverse = !reverse;\n }\n \n Set<String> temp = new HashSet<>(); \n \n for (String s : forward) {\n visited.add(s);\n \n for (String next : getNext(s)) {\n if (forward.contains(next) || visited.contains(next)) continue;\n if (backward.contains(next)) {\n found = true;\n intersect.add(next);\n }\n \n temp.add(next);\n \n if (reverse) {\n backwardMap.putIfAbsent(next, new ArrayList<>());\n backwardMap.get(next).add(s);\n } else {\n forwardMap.putIfAbsent(next, new ArrayList<>());\n forwardMap.get(next).add(s);\n }\n }\n }\n \n forward = temp;\n }\n \n return intersect;\n }\n \n private void trimForwardMap() {\n Deque<String> queue = new LinkedList<>();\n intersect.stream().forEach(s -> queue.offerLast(s));\n \n Set<String> visited = new HashSet(intersect);\n \n while (!queue.isEmpty()) {\n String s = queue.pollFirst();\n if (!forwardMap.containsKey(s)) return; // reach beginword\n \n for (String p : forwardMap.get(s)) {\n pathMap.putIfAbsent(p, new ArrayList<>());\n pathMap.get(p).add(s);\n \n if (visited.add(p)) queue.offerLast(p);\n }\n }\n return;\n }\n \n private void trimBackwardMap() {\n Deque<String> queue = new LinkedList<>();\n intersect.stream().forEach(s -> queue.offerLast(s));\n \n Set<String> visited = new HashSet(intersect);\n \n while (!queue.isEmpty()) {\n String s = queue.pollFirst();\n if (!backwardMap.containsKey(s)) return; // reach endWord\n \n for (String d : backwardMap.get(s)) {\n pathMap.putIfAbsent(s, new ArrayList<>());\n pathMap.get(s).add(d);\n \n if (visited.add(d)) queue.offerLast(d);\n }\n }\n return;\n }\n \n private List<String> getNext(String s) {\n char[] arr = s.toCharArray();\n List<String> nbs = new ArrayList<>();\n \n for (int i = 0; i < arr.length; i++) {\n char ch = arr[i];\n for (char c = \'a\'; c <= \'z\'; c++) {\n if (c == ch) continue;\n arr[i] = c;\n String nb = new String(arr);\n if (dict.contains(nb)) nbs.add(nb);\n }\n arr[i] = ch;\n }\n \n return nbs;\n }\n}\n``` | 13 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Java'] | 0 |
word-ladder-ii | C++ BFS with detailed explanation and illustration | c-bfs-with-detailed-explanation-and-illu-y1wp | Key points: graph & partial BFS. DO NOT use matrix to represent a network!!!!\nThe following content is based on the instance the problem gives.\nAllow me to s | charles1791 | NORMAL | 2020-06-12T05:28:45.479620+00:00 | 2020-06-14T01:50:02.892648+00:00 | 987 | false | Key points: graph & partial BFS. DO NOT use matrix to represent a network!!!!\nThe following content is based on the instance the problem gives.\nAllow me to show you a picture first:\n\nFor every two words, if they only have one different character, they are called "neighbors" and we could draw an edge between them just like the picture shows above. Each number beside the word indicates the number of steps we need to walk starting from the beginWord, namely the distance. Follow the numbers and edges, we could easily find all routes. So our job is to build a network like this and list all the routes (if exist).\n\n1. Build a network and store it with vector<int>[]\n\tWe need to create a list containing wordList.size() vectors; each vector stores the index of neighbors. (Warning: using matrix would cause "Time Limit Exceeded".) For every word, check out whether other words are its neighbors and if yes add their indexs to the vector. \n\tThe function of judging neighbors is here:\n\t```\n\tbool isANeighbor(string& s1, string& s2) {\n\t\tbool hasChanged = false;\n\t\tfor (int i = 0; i < s1.size(); i++) {\n\t\t\tif (s1[i] != s2[i]) {\n\t\t\t\tif (hasChanged)\n\t\t\t\t\treturn false;\n\t\t\t\telse\n\t\t\t\t\thasChanged = true;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\t```\n\tTo create a list:\n\t```\n\twordList.push_back(beginWord);\n\tint size = wordList.size();\n\tvector<int>* neighbors = new vector<int>[size];\n\tint ewordindex = -1;\n\tfor (int i = 0; i < size; i++) {\n\t\t\tif (wordList[i] == endWord)\n\t\t\t\tewordindex = i;\n\t\t\tfor (int j = i + 1; j < size; j++) {\n\t\t\t\tif (isANeighbor(wordList[i],wordList[j])) {\n\t\t\t\t\tneighbors[i].push_back(j);\n\t\t\t\t\tneighbors[j].push_back(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t```\n\tNow we have an array like this:\n\nIt demonstrates:\n\n\n2. BFS untill we find the endWord\nThere\'s nothing need to say, we just need to memorize each word\'s precursor, which we would use to create a route. \n```\nvector<int> steps(size);//memorize distances\nqueue<int> line;//BFS\nsteps[size - 1] = 1;\nline.push(size - 1);//add the index of the beginWord to the queue\nprecursor = new vector<int>[size];//a word could have multiple precursors\nwhile (!line.empty()) {\n\tint pos = line.front();\n\tline.pop();\n\tif (wordList[pos] == endWord)\n\t\t//we stop here because we are looking for the shortest routes\n\t\tbreak;\n\tfor (int i = 0; i < neighbors[pos].size(); i++) {\n\t\tif (steps[neighbors[pos][i]]==0) {\n\t\t\t//we have never visited here\n\t\t\tsteps[neighbors[pos][i]] = steps[pos] + 1;\n\t\t\tprecursor[neighbors[pos][i]].push_back(pos);\n\t\t\tline.push(neighbors[pos][i]);\n\t\t}\n\t\telse if (steps[neighbors[pos][i]] == steps[pos] + 1)\n\t\t\t//we have been here but there\'s another route to get here having the SAME distance\n\t\t\t//so this word have multiple precursors\n\t\t\tprecursor[neighbors[pos][i]].push_back(pos);\n\t}\n\n}\n```\n\n3. generate the route\nUsing precursor to trace back, nothing need to say.\n\nHere\'s my complete code:\n```\nclass Solution {\npublic:\n\tvector<int>* precursor;\n\tvector<vector<string>> res;\n\tbool isANeighbor(string& s1, string& s2) {\n\t\tbool hasChanged = false;\n\t\tfor (int i = 0; i < s1.size(); i++) {\n\t\t\tif (s1[i] != s2[i]) {\n\t\t\t\tif (hasChanged)\n\t\t\t\t\treturn false;\n\t\t\t\telse\n\t\t\t\t\thasChanged = true;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\tvoid generateRoute(vector<string> right, vector<int>& precursor2, vector<string>& wordList) {\n\t\tif (precursor2.size() == 0) {\n\t\t\tres.push_back(right);\n\t\t\treturn;\n\t\t}\n\t\tvector<string> copy;\n\t\tfor (int i = 0; i < precursor2.size(); i++) {\n\t\t\tcopy = right;\n\t\t\t// insert before the begin() cause we are back-tracing.\n\t\t\tcopy.insert(copy.begin(), wordList[precursor2[i]]);\n\t\t\tgenerateRoute(copy, precursor[precursor2[i]], wordList);\n\t\t}\n\t\n\t}\n\tvector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n\t\twordList.push_back(beginWord);\n\t\tint size = wordList.size();\n\t\tvector<int>* neighbors = new vector<int>[size];\n\t\tint ewordindex = -1;\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tif (wordList[i] == endWord)\n\t\t\t\tewordindex = i;\n\t\t\tfor (int j = i + 1; j < size; j++) {\n\t\t\t\tif (isANeighbor(wordList[i],wordList[j])) {\n\t\t\t\t\tneighbors[i].push_back(j);\n\t\t\t\t\tneighbors[j].push_back(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvector<int> steps(size);//memorize distances\n\t\tqueue<int> line;//BFS\n\t\tsteps[size - 1] = 1;\n\t\tline.push(size - 1);//add the index of the beginWord to the queue\n\t\tprecursor = new vector<int>[size];\n\t\twhile (!line.empty()) {\n\t\t\tint pos = line.front();\n\t\t\tline.pop();\n\t\t\tif (wordList[pos] == endWord)\n\t\t\t\t//we stop here because we are looking for the shortest routes\n\t\t\t\tbreak;\n\t\t\tfor (int i = 0; i < neighbors[pos].size(); i++) {\n\t\t\t\tif (steps[neighbors[pos][i]]==0) {\n\t\t\t\t\t//we have never visited here\n\t\t\t\t\tsteps[neighbors[pos][i]] = steps[pos] + 1;\n\t\t\t\t\tprecursor[neighbors[pos][i]].push_back(pos);\n\t\t\t\t\tline.push(neighbors[pos][i]);\n\t\t\t\t}\n\t\t\t\telse if (steps[neighbors[pos][i]] == steps[pos] + 1)\n\t\t\t\t\t//there\'s another route to get here and it has the SAME distance\n\t\t\t\t\tprecursor[neighbors[pos][i]].push_back(pos);\n\t\t\t}\n\t\t\n\t\t}\n\t\tif (ewordindex == -1 || steps[ewordindex] == 0)\n\t\t\treturn res;\n\t\tvector<string> right{endWord};\n\t\tgenerateRoute(right,precursor[ewordindex] , wordList);\n\t\treturn res;\n\t}\n};\n```\n\n\n | 13 | 1 | [] | 1 |
word-ladder-ii | [Python] Three steps approach | python-three-steps-approach-by-sotheanit-h2nx | This is an implmentation of a solution provided here.\n\nSolution:\nThe initial instinct is to used BFS to find shortest paths and keep generating partial paths | SotheanithSok | NORMAL | 2022-08-14T08:03:50.391440+00:00 | 2022-08-15T04:38:19.388846+00:00 | 1,061 | false | This is an implmentation of a solution provided [here](https://leetcode.com/problems/word-ladder-ii/discuss/2367587/Python-BFS-%2B-DFS-With-Explanation-Why-Optimization-Is-Needed-to-Not-TLE).\n\n**Solution**:\nThe initial instinct is to used BFS to find shortest paths and keep generating partial paths as we go from one level to another. However, this approach would cause TLE because we end up creating and destroying a lot of paths. Thus, we will avoid this problem by performing these three steps:\n\n1. **Adjacency List**: We start by generating adjacency list mapped pattern to words. This approach is better than replacing each character in a word with every lower case alphabets because we avoid checking all 26 alphabets for every character. \n\n```\n i.e. wordList = ["hot","dot","dog","lot","log","cog"]\n adj = {\n \'*ot\': [\'hot\', \'dot\', \'lot\'], \n \'h*t\': [\'hot\'], \n \'ho*\': [\'hot\'], \n \'d*t\': [\'dot\'], \n \'do*\': [\'dot\', \'dog\'], \n \'*og\': [\'dog\', \'log\', \'cog\'], \n \'d*g\': [\'dog\'], \n \'l*t\': [\'lot\'], \n \'lo*\': [\'lot\', \'log\'], \n \'l*g\': [\'log\'], \n \'c*g\': [\'cog\'], \n \'co*\': [\'cog\']\n }\n```\n\n2. **BFS**: Using the adjacency list generated in the previous step, we will traverse such list using BFS from beginWord to endWord and built a reversed adjacency list. The reversed adjacency list will map a word to all words that leading to it. \n\n\tIn order to account for all paths leading to a word while preventing adding duplicate next word to the queue, we will use two sets: Visited and VisitedCurrentLevel. \n\t\n\tVisited set will be used to keep track of all words used in previous levels. Current word that isn\'t in such set will be added to the reversed adjacency list. \nNext, the VisitedCurrentLevel will be used to keep track of all words used in the current level. A next word will only be added to a queue if it doesn\'t exist in such set. \n \n\tAfter processing each level, we will merge the VisitedCurrentLevel set into the Visited set.\n\n```\n i.e. reversedAdj = {\n \'hot\': [\'hit\'], \n \'dot\': [\'hot\'], \n \'lot\': [\'hot\'], \n \'dog\': [\'dot\'], \n \'log\': [\'lot\'], \n \'cog\': [\'dog\', \'log\']\n }\n```\n\n3. **DFS**: Use dfs to traverse the reversed adjacency list from endWord to beginWord and use a single queue to maintain constructed path. We add a next word to the front of the queue before we recursively go to such word and remove such word from the front of queue as we return. Once, the first word is equal to the beginWord, we have succesfully constructed a path. \n\n```\n i.e. res = [\n [\'hit\', \'hot\', \'dot\', \'dog\', \'cog\'], \n [\'hit\', \'hot\', \'lot\', \'log\', \'cog\']\n ]\n```\n\n**Complexity**:\n```\n\tTime:\n\t\t1. AdjacencyList: O(nw) where n is length of wordList and w is the length of each word\n\t\t2. BFS: O(n)\n\t\t3. DFS: O(n)\n\tSpace:\n 1. AdjacencyList: O(nw) where n is length of wordList and w is the length of each word\n 2. BFS: O(n)\n 3. DFS: O(n)\n```\n\n```\nfrom collections import defaultdict, deque\n\n\nclass Solution:\n def findLadders(\n self, beginWord: str, endWord: str, wordList: list[str]\n ) -> list[list[str]]:\n\n # 1. Create adjacency list\n def adjacencyList():\n\n # Initialize the adjacency list\n adj = defaultdict(list)\n\n # Iterate through all words\n for word in wordList:\n\n # Iterate through all characters in a word\n for i, _ in enumerate(word):\n\n # Create the pattern\n pattern = word[:i] + "*" + word[i + 1 :]\n\n # Add a word into the adjacency list based on its pattern\n adj[pattern].append(word)\n\n return adj\n\n # 2. Create reversed adjacency list\n def bfs(adj):\n\n # Initialize the reversed adjacency list\n reversedAdj = defaultdict(list)\n\n # Initialize the queue\n queue = deque([beginWord])\n\n # Initialize a set to keep track of used words at previous level\n visited = set([beginWord])\n\n while queue:\n\n # Initialize a set to keep track of used words at the current level\n visitedCurrentLevel = set()\n\n # Get the number of words at this level\n n = len(queue)\n\n # Iterate through all words\n for _ in range(n):\n\n # Pop a word from the front of the queue\n word = queue.popleft()\n\n # Generate pattern based on the current word\n for i, _ in enumerate(word):\n\n pattern = word[:i] + "*" + word[i + 1 :]\n\n # Itereate through all next words\n for nextWord in adj[pattern]:\n\n # If the next word hasn\'t been used in previous levels\n if nextWord not in visited:\n\n # Add such word to the reversed adjacency list\n reversedAdj[nextWord].append(word)\n\n # If the next word hasn\'t been used in the current level\n if nextWord not in visitedCurrentLevel:\n\n # Add such word to the queue\n queue.append(nextWord)\n\n # Mark such word as visited\n visitedCurrentLevel.add(nextWord)\n\n # Once we done with a level, add all words visited at this level to the visited set\n visited.update(visitedCurrentLevel)\n\n # If we visited the endWord, end the search\n if endWord in visited:\n break\n\n return reversedAdj\n\n # 3. Construct paths based on the reversed adjacency list using DFS\n def dfs(reversedAdj, res, path):\n\n # If the first word in a path is beginWord, we have succesfully constructed a path\n if path[0] == beginWord:\n\n # Add such path to the result\n res.append(list(path))\n\n return res\n\n # Else, get the first word in a path\n word = path[0]\n\n # Find next words using the reversed adjacency list\n for nextWord in reversedAdj[word]:\n\n # Add such next word to the path\n path.appendleft(nextWord)\n\n # Recursively go to the next word\n dfs(reversedAdj, res, path)\n\n # Remove such next word from the path\n path.popleft()\n\n # Return the result\n return res\n\n # Do all three steps\n adj = adjacencyList()\n reversedAdj = bfs(adj)\n res = dfs(reversedAdj, [], deque([endWord]))\n\n return res\n``` | 12 | 0 | ['Python'] | 3 |
word-ladder-ii | ✔️ 100% Fastest Swift Solution | 100-fastest-swift-solution-by-sergeylesc-0dy3 | \nclass Solution {\n func findLadders(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> [[String]] {\n\t\tguard wordList.contains(endWord) els | sergeyleschev | NORMAL | 2022-04-11T06:31:42.167258+00:00 | 2022-04-11T06:33:26.513544+00:00 | 357 | false | ```\nclass Solution {\n func findLadders(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> [[String]] {\n\t\tguard wordList.contains(endWord) else { return [] }\n var wordSet = Set(wordList)\n var queue: [String] = [beginWord]\n\t\tvar words: [[String]] = []\n\t\tvar isLoopEnd = false\n\t\tvar res:[[String]] = []\n\t\tvar lastWords: [String] = [endWord]\n\t\tvar i = 0\n\n if wordSet.contains(beginWord) { wordSet.remove(beginWord) }\n\t\t\n loop: \n while queue.count > 0 {\n\t\t\tvar list: [String] = []\n\t\t\t\n for word in queue {\n\t\t\t\tlet next = nextWords(word, &wordSet)\n list += next\n\t\t\t\tif next.contains(endWord) { isLoopEnd = true }\n\t\t\t}\n\t\t\t\n if isLoopEnd { break loop } \n else {\n\t\t\t\tqueue = list\n\t\t\t\twords.append(queue)\n\t\t\t}\n\t\t}\n \n\t\twhile i < words.count - 1 {\n\t\t\tvar tmp = Set<String>()\n\t\t\tfor word0 in words[words.count - 1 - i] {\n\t\t\t\tfor word1 in lastWords where isNext(word0, word1) { tmp.insert(word0) }\n\t\t\t}\n\t\t\tlastWords = Array(tmp)\n\t\t\twords[words.count - 1 - i] = lastWords\n\t\t\ti += 1\n\t\t}\n \n\n\t\tfunc backtrack(_ path: [String], _ index: Int) {\n\t\t\tif index == words.count {\n if isNext(path[path.count - 1], endWord) { res.append(path + [endWord]) }\n\t\t\t\treturn\n\t\t\t}\n \n\t\t\tvar path = path\n\t\t\tfor word in words[index] {\n\t\t\t\tif isNext(path[path.count - 1], word) == false { continue }\n \n\t\t\t\tpath.append(word)\n\t\t\t\tbacktrack(path, index + 1)\n\t\t\t\tpath.remove(at: path.count - 1)\n\t\t\t}\n\t\t}\n \n\t\tbacktrack([beginWord], 0)\n\t\treturn res\n\t}\n\n \n\tfunc isNext(_ word0: String, _ word1: String) -> Bool {\n\t\tlet chars0 = Array(word0)\n\t\tlet chars1 = Array(word1)\n\t\tvar count = 0\n\t\t\n for i in 0..<word0.count {\n\t\t\tif chars0[i] != chars1[i] {\n\t\t\t\tcount += 1\n\t\t\t\tif count > 1 { return false }\n\t\t\t}\n\t\t}\n\t\t\n return count == 1\n\t}\n\n \n\tfunc nextWords(_ word: String, _ wordSet: inout Set<String>) -> [String] {\n\t\tvar res: [String] = []\n\t\tvar chars = Array(word)\n\t\tlet alphabeta = Array("abcdefghijklmnopqrstvuwxyz")\n\t\t\n for (i, char) in chars.enumerated() {\n\t\t\tfor c in alphabeta {\n\t\t\t\tif c == char { continue } \n\t\t\t\telse {\n\t\t\t\t\tchars[i] = c\n\t\t\t\t\tlet string = String(chars)\n\t\t\t\t\tif wordSet.contains(string) {\n\t\t\t\t\t\tres.append(string)\n\t\t\t\t\t\twordSet.remove(string)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n chars[i] = char\n\t\t\t}\n\t\t}\n\t\t\n return res\n\t}\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 12 | 0 | ['Swift'] | 0 |
word-ladder-ii | JavaScript easy to understand solution using BFS + DFS | javascript-easy-to-understand-solution-u-07ib | The idea is the following:\n1. Do BFS from endWord to beginWord, and compute the distance from each word to the endWord. In the meantime, we can also construct | zhenyi2697 | NORMAL | 2019-09-23T20:14:52.493756+00:00 | 2019-09-23T20:14:52.493808+00:00 | 1,942 | false | The idea is the following:\n1. Do BFS from endWord to beginWord, and compute the distance from each word to the endWord. In the meantime, we can also construct the mapping from one word to another, to avoid recomputing the combination again on step 2.\n2. Do DFS with backtracing from startWord to endWord, and only go further if next word\'s distance equal current distance + 1\n\n```\n/**\n * @param {string} beginWord\n * @param {string} endWord\n * @param {string[]} wordList\n * @return {string[][]}\n */\nvar findLadders = function(beginWord, endWord, wordList) {\n const wordSet = new Set(wordList);\n wordSet.add(beginWord);\n \n if (!wordSet.has(endWord)) return [];\n \n const distanceMap = new Map();\n const wordMap = new Map();\n \n // 1. BFS construct distanceMap and wordMap from end to start\n const queue = [];\n const visited = new Set();\n \n // Flag to check if we can reach start from end\n let reached = false;\n \n queue.push(endWord);\n visited.add(endWord);\n let distance = 0;\n distanceMap.set(endWord, distance);\n while(queue.length !== 0) {\n let size = queue.length;\n distance++;\n for(let i = 0; i < size; i++) {\n const word = queue.shift();\n for(let w of getNextWords(word, wordSet)) {\n // push into wordMap from start to end\n // we need to push here before visited check\n if (!wordMap.has(w)) wordMap.set(w, []);\n wordMap.get(w).push(word);\n \n if (visited.has(w)) continue;\n if (w === beginWord) reached = true;\n \n // put into distance map\n distanceMap.set(w, distance);\n \n queue.push(w);\n visited.add(w);\n }\n }\n }\n \n // short circuit if can not reach\n if (!reached) return [];\n \n // 2. DFS find path where distance - 1\n const result = [];\n dfs(result, [beginWord], beginWord, endWord, wordMap, distanceMap);\n \n return result;\n};\n\nvar dfs = function(result, tmpPath, word, endWord, wordMap, distanceMap) {\n if (word === endWord) {\n result.push([...tmpPath]);\n return;\n }\n \n for (let nextWord of wordMap.get(word)) {\n if (distanceMap.get(word) === distanceMap.get(nextWord) + 1) {\n tmpPath.push(nextWord);\n dfs(result, tmpPath, nextWord, endWord, wordMap, distanceMap);\n tmpPath.pop();\n }\n }\n}\n\nvar getNextWords = function(word, wordSet) {\n const result = [];\n for (let i = 0; i < word.length; i++) {\n let currentCode = word.charCodeAt(i);\n for (let c = 97; c <= 122; c++) {\n if (c !== currentCode) {\n const chars = word.split(\'\');\n chars[i] = String.fromCharCode(c);\n let newWord = chars.join(\'\');\n if (wordSet.has(newWord)) {\n result.push(newWord);\n }\n }\n }\n } \n\n return result;\n}\n\n``` | 12 | 0 | ['Backtracking', 'JavaScript'] | 3 |
word-ladder-ii | [C++] Easy BFS + building Graph then simple DFS | c-easy-bfs-building-graph-then-simple-df-1gtc | \nclass Solution {\npublic:\n\t// read this function after reading the main function\n unordered_map<string, vector<string>> adj;\n void dfs(string node, | Rxnjeet | NORMAL | 2022-08-14T15:56:54.580521+00:00 | 2022-08-15T06:44:59.922344+00:00 | 2,015 | false | ```\nclass Solution {\npublic:\n\t// read this function after reading the main function\n unordered_map<string, vector<string>> adj;\n void dfs(string node, vector<vector<string>> &ans, vector<string> &curr, string beginWord)\n {\n if(node == beginWord)\n {\n ans.push_back(curr);\n return;\n }\n \n for(string &nbr : adj[node])\n {\n curr.push_back(nbr);\n dfs(nbr, ans, curr, beginWord);\n curr.pop_back();\n }\n }\n\t\n\t// main function\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) \n {\n vector<vector<string>> ans;\n \n unordered_map<string, int> list;\n\t\t// shortest distance to reach the current word\n for(string &word : wordList) list[word] = INT_MAX;\n \n\t\t// we can never reach endWord in this case\n if(list.find(endWord) == list.end()) return ans;\n \n queue<string> q;\n \n q.push(beginWord);\n int level = 0;\n \n\t\t// straight forward BFS\n while(!q.empty())\n {\n int n = q.size();\n\t\t\t// distance to reach the current node (from beginWord)\n ++level;\n for(int i=0; i<n; ++i)\n {\n string front = q.front();\n q.pop();\n \n\t\t\t\t// generating all possible words that differ from the current word at a single position\n for(int j=0; j<front.size(); ++j)\n {\n string newWord = front;\n \n for(char letter=\'a\'; letter<=\'z\'; ++letter)\n {\n newWord[j] = letter;\n \n\t\t\t\t\t\t// if the newWord is not visited or is visited on this level then only proceed \n\t\t\t\t\t\t// o/w there\'s no sense of proceeding because we have already reached \n\t\t\t\t\t\t// the word in less no. of steps\n\t\t\t\t\t\t\n if(newWord != front && list.find(newWord) != list.end() && list[newWord] >= level)\n {\n\t\t\t\t\t\t\t// building the graph in reverse order (we will know the reason for this later)\n\t\t\t\t\t\t\t// i.e making a edge between [u, v] in u <-- v this order.\n adj[newWord].push_back(front);\n \n\t\t\t\t\t\t\t// the newWord has been discovered in this level only, \n\t\t\t\t\t\t\t// since this has been happended the path from this newWord to endWord \n\t\t\t\t\t\t\t// will be same for both the cases thus not proceeding any further\n if(list[newWord] == level) continue;\n \n list[newWord] = level;\n \n if(newWord != endWord) q.push(newWord);\n }\n }\n }\n }\n }\n vector<string> curr({endWord});\n dfs(endWord, ans, curr, beginWord);\n\t\t// because all the paths generated from dfs are from endWord->beginWord\n for(int i=0; i<ans.size(); ++i) reverse(ans[i].begin(), ans[i].end());\n \n\t\t// upd : Why are we building the graph in the opposite manner ?\n\t\t// it is an unnecessary thing to do. we can acutally build the graph in normal order\n\t\t// and can save our time in reversing them later on which i did.\n\t\t\n return ans;\n }\n};\n```\n* Credits for update @shagunnnn | 11 | 0 | ['Depth-First Search', 'Breadth-First Search', 'C', 'C++'] | 3 |
word-ladder-ii | C++ Full Explained Clean Code No TLE | c-full-explained-clean-code-no-tle-by-da-xw77 | The idea of this problem is to run bfs, where one step is changing some letter of word. For me easier to separate problem to two parts:\n\n1. Create graph of co | DarshanAgarwal95 | NORMAL | 2022-08-14T02:33:50.337971+00:00 | 2022-08-14T02:33:50.338004+00:00 | 4,234 | false | The idea of this problem is to run bfs, where one step is changing some letter of word. For me easier to separate problem to two parts:\n\n1. Create graph of connections G.\n2. Run bfs on this graph with collecting all possible solutions.\nNow, let us consider steps in more details.\n\n1. To create graph of connections for each word, for example hit, create patterns *it, h*t, hi*. Then iterate over patterns and connect words in our defaultdict G.\n\n2. We need to run bfs, but we also need to give as answer all possible solutions, so, we need to modify our algorithm a bit. We keep two dictionaries: deps for depths of each word and paths to keep all possible paths. When we extract element from queue and look at its neighbours, we need to add new element to queue if deps[neib] == -1. Also we need to update paths[neib] if deps[neib] == -1 or deps[neib] == deps[w] +, that is to deal with all ways of optimal length.\n\n**Complexity**\n\nWe need O(nk^2) time to create all possible patterns: for each of n words we have k patterns with length k. Then we will have no more than O(n*k*26) possible connections for all pairs of words, each of which has length k, so to create G we need O(nk^2*26) time. In practice thought this number is smaller, because graph can not have this number of connections. For the last part with bfs we have complexity O(nk^2*26) again, because this is the number of edges in our graph + A, where A is number of found solutions, which can be exponential. So, time complexity is O(nk^2*26 + A), space is the same\n\n\n```\nclass Solution {\npublic:\n vector<int>* precursor;\n\tvector<vector<string>> res;\n\tbool isANeighbor(string& s1, string& s2) {\n\t\tbool hasChanged = false;\n\t\tfor (int i = 0; i < s1.size(); i++) {\n\t\t\tif (s1[i] != s2[i]) {\n\t\t\t\tif (hasChanged)\n\t\t\t\t\treturn false;\n\t\t\t\telse\n\t\t\t\t\thasChanged = true;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\tvoid generateRoute(vector<string> right, vector<int>& precursor2, vector<string>& wordList) {\n\t\tif (precursor2.size() == 0) {\n\t\t\tres.push_back(right);\n\t\t\treturn;\n\t\t}\n\t\tvector<string> copy;\n\t\tfor (int i = 0; i < precursor2.size(); i++) {\n\t\t\tcopy = right;\n\t\t\t// insert before the begin() cause we are back-tracing.\n\t\t\tcopy.insert(copy.begin(), wordList[precursor2[i]]);\n\t\t\tgenerateRoute(copy, precursor[precursor2[i]], wordList);\n\t\t}\n\t\n\t}\n\tvector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n\t\twordList.push_back(beginWord);\n\t\tint size = wordList.size();\n\t\tvector<int>* neighbors = new vector<int>[size];\n\t\tint ewordindex = -1;\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tif (wordList[i] == endWord)\n\t\t\t\tewordindex = i;\n\t\t\tfor (int j = i + 1; j < size; j++) {\n\t\t\t\tif (isANeighbor(wordList[i],wordList[j])) {\n\t\t\t\t\tneighbors[i].push_back(j);\n\t\t\t\t\tneighbors[j].push_back(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvector<int> steps(size);//memorize distances\n\t\tqueue<int> line;//BFS\n\t\tsteps[size - 1] = 1;\n\t\tline.push(size - 1);//add the index of the beginWord to the queue\n\t\tprecursor = new vector<int>[size];\n\t\twhile (!line.empty()) {\n\t\t\tint pos = line.front();\n\t\t\tline.pop();\n\t\t\tif (wordList[pos] == endWord)\n\t\t\t\t//we stop here because we are looking for the shortest routes\n\t\t\t\tbreak;\n\t\t\tfor (int i = 0; i < neighbors[pos].size(); i++) {\n\t\t\t\tif (steps[neighbors[pos][i]]==0) {\n\t\t\t\t\t//we have never visited here\n\t\t\t\t\tsteps[neighbors[pos][i]] = steps[pos] + 1;\n\t\t\t\t\tprecursor[neighbors[pos][i]].push_back(pos);\n\t\t\t\t\tline.push(neighbors[pos][i]);\n\t\t\t\t}\n\t\t\t\telse if (steps[neighbors[pos][i]] == steps[pos] + 1)\n\t\t\t\t\t//there\'s another route to get here and it has the SAME distance\n\t\t\t\t\tprecursor[neighbors[pos][i]].push_back(pos);\n\t\t\t}\n\t\t\n\t\t}\n\t\tif (ewordindex == -1 || steps[ewordindex] == 0)\n\t\t\treturn res;\n\t\tvector<string> right{endWord};\n\t\tgenerateRoute(right,precursor[ewordindex] , wordList);\n\t\treturn res;\n }\n};\n```\n\n\n\n\n**IF YOU LIKE IT THEN PLEASE PLEASE UPVOTE IT** | 11 | 3 | ['Breadth-First Search', 'C', 'C++'] | 0 |
word-ladder-ii | [Python] Slow but easy to understand for beginners | python-slow-but-easy-to-understand-for-b-n4tg | \nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: list[str]) -> list[list[str]]:\n alphabet = "abcdefghijklmnopqrstuvw | jozef-hudec-27 | NORMAL | 2021-07-24T08:15:04.507721+00:00 | 2021-07-24T08:16:44.590978+00:00 | 477 | false | ```\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: list[str]) -> list[list[str]]:\n alphabet = "abcdefghijklmnopqrstuvwxyz"\n wordList = set(wordList) # making wordList a set so we can look-up a word in O(1) time\n if beginWord == endWord:\n return [beginWord] # if beginWord is the same as endWord we just return [beginWord] because there won\xB4t be a shorter path\n q = collections.deque([[beginWord, []]])\n res = []\n while q:\n word, path = q.popleft() # word is the current word we\xB4re on, path is the path that led us to this word\n if word in wordList:\n wordList.remove(word) # deleting the current word from wordList because we don\xB4t want to go back\n if word == endWord:\n if not res or len(path) + 1 == len(res[0]): \n res.append(path + [word])\n elif len(path) + 1 > len(res[0]): # if the path that led us to this endWord is longer than the one in res, we know it\xB4s longer and\n break # all possible future paths will be longer so there\xB4s no point in continuing\n else: # if the word isn\xB4t endWord we find all words that differ by one character and continue in searching\n for i in range(len(word)):\n for letter in alphabet:\n next_word = word[:i] + letter + word[i+1:]\n if next_word in wordList:\n q.append([next_word, path + [word]])\n return res\n```\n\n\nIf you liked this solution, please upvote! :) | 11 | 2 | ['Python'] | 2 |
word-ladder-ii | Input None Output None , 1/1 Test Case Passed Wrong Answer | input-none-output-none-11-test-case-pass-pd22 | When I submit the code below, OJ tells me that the input was NONE, output was NONE , 1/1 test case passed and the answer is WRONG. I am not sure how to diagnose | sj482 | NORMAL | 2015-09-08T05:07:57+00:00 | 2015-09-08T05:07:57+00:00 | 2,128 | false | When I submit the code below, OJ tells me that the input was NONE, output was NONE , 1/1 test case passed and the answer is WRONG. I am not sure how to diagnose this problem . \n\nDid anyone else face this issue?\n\n public class Solution {\n \tpublic List<String> getNeighbors(String str, Set<String> dict){\n \t\tList<String> result = new ArrayList<String>();\n \t\tfor(int i = 0; i < str.length() ; i++){\n \t\t\tfor(int j = 0 ; j < 26 ;j ++){\n \t\t\t\tStringBuilder sb = new StringBuilder(str);\n \t\t\t\tchar c = (char) ('a' + j);\n \t\t\t\tif(str.charAt(i) != c){\n \t\t\t\t\tsb.setCharAt(i, c);\n \t\t\t\t\tString s = sb.toString();\n \t\t\t\t\tif(dict.contains(s)){\n \t\t\t\t\t\tresult.add(s);\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t\treturn result;\n \t}\n \n \tpublic List<List<String>> findLadders(String start, String end, Set<String> wordList) {\n \t\tList<List<String>> result = new ArrayList<List<String>>();\n \t\t\n \t\tQueue<String> wordQueue = new LinkedList<String>();\n \t\twordQueue.add(start);\n \t\tSet<String> wordsUsed = new HashSet<String>();\n \t\twordsUsed.add(start);\n \t\twordList.add(end);\n \t\tMap<String,List<String>> incoming = new HashMap<String, List<String>>();\n \t\t\n \t\t// build the incoming map \n \t\twhile(!wordQueue.isEmpty()){\n \t\t\tString word = wordQueue.remove();\n \t\t\tif(word.equals(end)){\n \t\t\t\tbreak;\n \t\t\t}\n \t\t\tfor(String neigh : getNeighbors(word, wordList)){\n \t\t\t\tif(!wordsUsed.contains(neigh)){\n \t\t\t\t\twordsUsed.add(neigh);\n \t\t\t\t\tif(!incoming.containsKey(neigh)){\n \t\t\t\t\t\tincoming.put(neigh, new ArrayList<String>());\n \t\t\t\t\t}\n \t\t\t\t\tincoming.get(neigh).add(word);\n \t\t\t\t\twordQueue.add(neigh);\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t\t\n \t\t//DFS the incoming map to get all the paths\n \t\tbuildPathsDFS( end, start, incoming, result,new ArrayList<String>());\n \t\t\n \t\treturn result;\n \t}\n \t\n \tpublic void buildPathsDFS(String start, String end, Map<String,\n \t\t\tList<String>> incoming,List<List<String>> result,List<String> curPath){\n \n \t\tif(start.equals(end)){\n \t\t\tcurPath.add(end);\n \t\t\tList<String> temp = new ArrayList<String>(curPath);\n \t\t\tCollections.reverse(temp);\n \t\t\tresult.add(temp);\n \t\t\tcurPath.remove(end);\n \t\t\treturn;\n \t\t}\n \n \t\tif(incoming.containsKey(start)){\n \t\t\tcurPath.add(start);\n \t\t\tfor(String next : incoming.get(start)){\n \t\t\t\tbuildPathsDFS(next, end, incoming, result, curPath);\n \t\t\t}\n \t\t\tcurPath.remove(start);\n \t\t}\n \t}\n \t\n } | 11 | 0 | [] | 4 |
word-ladder-ii | Python 3, BFS + DFS BACKTRACKING no TLE | python-3-bfs-dfs-backtracking-no-tle-by-cc2jt | First, I use bfs and traverser layer by layer but get memory limit exceeded. Then I try to build the link between the child and parent and reconstruct via DFS | ladykkk | NORMAL | 2022-08-15T22:27:23.409593+00:00 | 2022-08-15T22:28:17.595697+00:00 | 363 | false | First, I use bfs and traverser layer by layer but get memory limit exceeded. Then I try to build the link between the child and parent and reconstruct via DFS to avoid store all the paths and computing same path again and again.\n```\ndef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n graph = collections.defaultdict(list)\n words = set(wordList)\n if endWord not in words: return []\n words.discard(beginWord)\n q = {beginWord}\n while q:\n nq = set()\n for word in q:\n for c in "abcdefghijklmnopqrstuvwxyz":\n for i in range(len(word)):\n nw = word[:i] + c + word[i+1:]\n if nw in words:\n graph[nw].append(word)\n nq.add(nw)\n words -= set(graph.keys())\n q = nq\n \n # use DFS to reconstruct the path from end to begin\n def dfs(word):\n if word == beginWord:\n return [[beginWord]]\n res = []\n for w in graph[word]:\n res += [k + [word] for k in dfs(w)]\n return res\n\t\t\t\n return dfs(endWord) | 10 | 0 | [] | 1 |
word-ladder-ii | C++ two approaches | c-two-approaches-by-sunhaozhe-ez49 | BFS with queue of paths\n\n Runtime: 480 ms, faster than 39.48%\n Memory Usage: 178.1 MB, less than 45.00%\n\nc++\n\tvector<vector<string>> findLadders(string b | sunhaozhe | NORMAL | 2020-03-14T22:37:11.707797+00:00 | 2020-03-14T22:44:51.515074+00:00 | 2,240 | false | # BFS with queue of paths\n\n* Runtime: 480 ms, faster than 39.48%\n* Memory Usage: 178.1 MB, less than 45.00%\n\n```c++\n\tvector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n vector<vector<string>> res;\n unordered_set<string> d(wordList.begin(), wordList.end());\n if(d.count(endWord) == 0) return res;\n queue<vector<string>> q;\n q.push({beginWord});\n d.insert(endWord);\n bool flag = false;\n while(!q.empty()){\n int q_size = q.size();\n unordered_set<string> visited;\n for(int i = 0; i < q_size; i++){\n auto curr = q.front();\n string word = curr.back();\n q.pop();\n for(int j = 0; j < word.size(); j++){\n for(char c = \'a\'; c <= \'z\'; c++){\n auto tmp = word[j];\n word[j] = c;\n if(d.count(word) != 0){\n vector<string> nxt = curr;\n nxt.push_back(word);\n q.push(nxt);\n visited.insert(word);\n if(word == endWord){\n flag = true;\n res.push_back(nxt);\n }\n }\n word[j] = tmp;\n }\n }\n }\n if(flag) break;\n for(auto w: visited) d.erase(w);\n }\n return res;\n }\n```\n\n\n***************************************************************************************************\n\n# BFS combined with DFS\n\nFirst use BFS to mark distance between `beginWord` and each word in `wordList`, then run DFS to collect the shortest paths. \n\n* Runtime: 112 ms, faster than 91.17%\n* Memory Usage: 21.2 MB, less than 85.00%\n\n```c++\n\tvoid bfs(string& beginWord, string& endWord, unordered_set<string>& d, unordered_map<string, vector<string>>& neighbors, unordered_map<string, int>& dist){\n queue<string> q;\n q.push(beginWord);\n dist[beginWord] = 0;\n int lvl = 1;\n while(!q.empty()){\n int q_size = q.size();\n unordered_set<string> visited;\n for(int i = 0; i < q_size; i++){\n auto curr = q.front();\n q.pop();\n string nxt = curr;\n for(int j = 0; j < nxt.size(); j++){\n auto tmp = nxt[j];\n for(char c = \'a\'; c <= \'z\'; c++){\n nxt[j] = c;\n if(d.count(nxt) != 0){\n neighbors[curr].push_back(nxt);\n visited.insert(nxt);\n if(dist.count(nxt) == 0){\n dist[nxt] = lvl;\n q.push(nxt);\n }\n }\n }\n nxt[j] = tmp;\n }\n }\n lvl++;\n for(string w: visited) d.erase(w);\n }\n }\n \n void dfs(string& curr, string& endWord, unordered_map<string, vector<string>>& neighbors, unordered_map<string, int>& dist, vector<string>& path, vector<vector<string>>& res){\n path.push_back(curr);\n if(curr == endWord){\n res.push_back(path);\n return;\n }\n for(auto nxt: neighbors[curr]){\n if(dist[nxt] == dist[curr] + 1){\n dfs(nxt, endWord, neighbors, dist, path, res);\n path.pop_back();\n }\n }\n }\n \n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n vector<vector<string>> res;\n unordered_set<string> d(wordList.begin(), wordList.end());\n if(d.count(endWord) == 0) return res;\n unordered_map<string, vector<string>> neighbors;\n unordered_map<string, int> dist;\n bfs(beginWord, endWord, d, neighbors, dist);\n vector<string> path;\n dfs(beginWord, endWord, neighbors, dist, path, res);\n return res;\n }\n```\n\n\n\n\n | 10 | 0 | ['Backtracking', 'Depth-First Search', 'Breadth-First Search', 'C++'] | 1 |
word-ladder-ii | C# creative idea to create a graph and then construct shortest path map practice in 2019 | c-creative-idea-to-create-a-graph-and-th-1hk6 | Sept. 12, 2019 8:49 PM\nIt is a hard level algorithm. I also like to learn the idea to build a graph using words, and then build a map to contain shortest path | jianminchen | NORMAL | 2019-09-10T06:28:00.579876+00:00 | 2019-10-15T18:26:35.215741+00:00 | 1,100 | false | Sept. 12, 2019 8:49 PM\nIt is a hard level algorithm. I also like to learn the idea to build a graph using words, and then build a map to contain shortest path to a word. \n\nWhat I like to practice in 2019 is to push myself to learn a few ideas using graph and also write down some analysis, build strong interest on the algorithm analysis and how to solve a hard level algorithm. \n\nI learn from my own experience to solve this hard level algorithm starting from 2016. I think that it is better to work on a simplified problems similar to word ladder II first. One of problems is to find all paths, not necessary minimimum length. I should learn how to write simple brute force solution, and using backtracking, marking visit efficiently. [Here](https://github.com/jianminchen/100-hard-level-algorithms-2018-summer-campaign/blob/master/leetcode%20126%20word%20ladder%20II/simple%20version%20for%20interview/DFS%20brute%20force.cs) is my practice in Sept., 2019. \n\nThis algorithm is a hard level one. What I do is to study one of discussion post in C#, and then I write down my analysis based on my past experience, debugging. I encourage myself to learn a few ideas to solve this hard level algorithm in 2019. This is the first one, without TLE bug. \n\n**Case study**\n\nI like to write down how to design the graph, and then apply BFS to build a shortest path map, solve the hard level algorithm. \n\nI like to work on the following test cases. \nsource = "good";\ndest = "best";\n\nA list of words { "bood", "beod", "besd", "goot", "gost", "gest", "best" };\n\ntwo paths\ngood->bood->beod->besd->best\ngood->goot->gost->gest->best\n\nThe above two paths both have minimum length 5. \n\n**More detail**\n\nEach word with length 4 has four keys. For example, word "good" can be searched using the following 4 keys:\n"\\*ood"\n"g\\*od"\n"go\\*d"\n"goo\\*". \n\nBy going over the start word and all words in dictionary, we can preprocess the graph to build all keys and related words. \n\nFor example, \n"*ood" can be searched by changing first char to \'a\' to \'z\', and \'g\' and \'b\' are in dictionary. So, \n\nKey = "*ood"\nvalues = {"good","bood"}. \n\n**BFS search more detail**\nGive the above example, start word from "good", end word is "best", we like to build shorest path from start word to every word encounted in BFS search, first, key is "good", then key is "bood","goot", and so on. \n\nOne highlight is to add more entries for same distance. We can argue that breadth first search, the first one found should have less and equal value, so new one should just check if it is equal or not. \n\nThe above logic is shown in the code. I put comment "reasoning?". \n\n**Time complexity**\nOne of my practices ran into time-limit-exceeded error. So it reminds me to pay attention to time complexity, and I find this study code and it should have better time complexity since no timeout. \n\nAll words in dictionary are preprocessed once to build the graph, with special key containing wild char . This makes the algorithm time efficient specially for large amount words in dictionary. \n\nWord dictionary with length = 5 can have maximum words 26^5 = 11,881,376, let us denote using N. So it is important to use algorithm with time complexity O(N), not above O(N). \n\n**Here are highlights:**\n\n1. Understand that it is important to apply BFS search starting from start word in order to find minimum length of path, and also meet the requirement of TLE concern. \n2. Preprocess the graph first, go over all words in dictionary to build a hashmap, so it will take O(1) to find all one hop away neighbors in the graph. \n3. Once the end word is visited, terminate the search in the graph. No need to go further to search. \n4. Design shortest path for each word visited, the path is defined from begin word to any word visited. To allow multiple path with same distance, argue that those visited and found first should have less and equal length. \n5. C# code using StringBuilder, operator [], good practice compared to using immutable string. \n\n**Some art**\n\nI do believe that it is a good idea to come out some very good art to present the process of algorithm design. This hard level algorithm is such an interesting algorithm. I like to start to work on the art to illustrate the problem solving starting from selected test cases, two minimum path from good to best, and then draw a queue, show what is order to get into queue, and then shortestPaths are calculated for each key. The shortest path is from "good" to key word. \n\nI will think about more later to make the art of diagram more memorable and helpful for me to learn the problem solving. \n\n\n\n\n```\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace _126_word_ladder_II\n{\n class Program\n {\n static void Main(string[] args)\n {\n var source = "good";\n var dest = "best";\n\n var words = new string[] { "bood", "beod", "besd", "goot", "gost", "gest", "best" };\n\n var result = FindLadders(source, dest, words);\n // two paths\n // good->bood->beod->besd->best\n // good->goot->gost->gest->best\n }\n\n /// <summary>\n /// Sept. 9, 2019\n /// study code\n /// https://leetcode.com/problems/word-ladder-ii/discuss/375730/C-BFS-Solution-faster-than-94-and-less-than-100-memory\n /// </summary>\n /// <param name="beginWord"></param>\n /// <param name="endWord"></param>\n /// <param name="wordList"></param>\n /// <returns></returns>\n public static IList<IList<string>> FindLadders(string beginWord, string endWord, IList<string> wordList)\n {\n var graph = new Dictionary<string, HashSet<string>>();\n\n preprocessGraph(beginWord, graph);\n\n foreach (var word in wordList)\n {\n preprocessGraph(word, graph);\n }\n\n //Queue For BFS\n var queue = new Queue<string>();\n\n //Dictionary to store shortest paths to a word\n var shortestPaths = new Dictionary<string, IList<IList<string>>>();\n\n queue.Enqueue(beginWord);\n // do not confuse () with {} - fix compiler error\n shortestPaths[beginWord] = new List<IList<string>>() { new List<string>() { beginWord } }; \n\n var visited = new HashSet<string>();\n\n while (queue.Count > 0)\n {\n var visit = queue.Dequeue();\n\n //we can terminate loop once we reached the endWord as all paths leads here already visited in previous level \n if (visit.Equals(endWord))\n {\n return shortestPaths[endWord];\n }\n \n if (visited.Contains(visit))\n continue;\n\n visited.Add(visit);\n\n //Transform word to intermediate words and find matches\n // case study: var source = "good"; \n // go over all keys related to visit = "good" for example,\n // keys: "*ood","g*od","go*d","goo*"\n for (int i = 0; i < visit.Length; i++)\n {\n var sb = new StringBuilder(visit);\n\n sb[i] = \'*\';\n\n var key = sb.ToString();\n\n if (!graph.ContainsKey(key))\n {\n continue;\n }\n \n //brute force all adjacent words\n foreach (var neighbor in graph[key])\n {\n if (visited.Contains(neighbor))\n {\n continue; \n }\n \n //fetch all paths leads current word to generate paths to adjacent/child node \n foreach (var path in shortestPaths[visit])\n {\n var newPath = new List<string>(path);\n\n newPath.Add(neighbor); // path increments one, before it is saved in shortestPaths\n\n if (!shortestPaths.ContainsKey(neighbor))\n {\n shortestPaths[neighbor] = new List<IList<string>>() { newPath };\n } // reasoning ? \n else if (shortestPaths[neighbor][0].Count >= newPath.Count) // // we are interested in shortest paths only\n {\n shortestPaths[neighbor].Add(newPath);\n }\n }\n\n queue.Enqueue(neighbor); \n } \n }\n }\n\n return new List<IList<string>>();\n }\n\n /// <summary>\n /// Time complexity is biggest challenge. It is a good idea to use O(N) time to preprocess a graph for the search. \n /// How to define the graph? It is kind of creative idea to use wildchar * to replace one char for each word.\n /// \n /// For example word "hit" can be written as "*it", "h*t", "hi*". \n /// graph["*it"] = new HashSet<string>{"hit"}\n /// graph["h*t"] = new HashSet<string>{"hit"}\n /// graph["hi*"] = new HashSet<string>{"hit"}\n /// \n /// git can be written as "*it", "g*t","gi*"\n /// so graph["*it"] = new HashSet<string>{"hit","git"}\n /// ...\n /// \n /// </summary>\n /// <param name="word"></param>\n /// <param name="graph"></param>\n private static void preprocessGraph(string word, Dictionary<string, HashSet<string>> graph)\n {\n //For example word hit can be written as *it,h*t,hi*. \n //This method genereates a map from each intermediate word to possible words from our wordlist\n for (int i = 0; i < word.Length; i++)\n {\n var sb = new StringBuilder(word);\n sb[i] = \'*\';\n\n var key = sb.ToString();\n\n if (graph.ContainsKey(key))\n {\n graph[key].Add(word);\n }\n else\n {\n var set = new HashSet<string>();\n set.Add(word);\n graph[key] = set;\n }\n }\n }\n }\n}\n``` | 10 | 0 | [] | 2 |
word-ladder-ii | the simplest javascript bfs solution | the-simplest-javascript-bfs-solution-by-yxoih | ```\nvar findLadders=function(beginWord, endWord, wordList){\n let results=[]\n let visited={}\n let steps=Number.MAX_SAFE_INTEGER\n let pathq=[[beg | deep666 | NORMAL | 2018-06-30T10:41:55.502381+00:00 | 2018-06-30T10:41:55.502381+00:00 | 1,056 | false | ```\nvar findLadders=function(beginWord, endWord, wordList){\n let results=[]\n let visited={}\n let steps=Number.MAX_SAFE_INTEGER\n let pathq=[[beginWord]]\n let wordset=new Set(wordList)\n while(pathq.length>0){\n let curpath=pathq.shift()\n let curword=curpath[curpath.length-1]\n if(curpath.length>=steps){\n break\n }\n for(let i = 97; i < 123; i++){\n for(let j=0;j<curword.length;j++){\n let w=curword.substring(0, j)+String.fromCharCode(i)+curword.substring(j+1)\n if(w!==curword&&wordset.has(w)){\n if(!visited[w]){\n pathq.push([...curpath,w])\n }\n if(w===endWord){\n if(curpath.length<steps){\n steps=curpath.length+1\n }\n results.push([...curpath,w])\n }\n }\n }\n }\n visited[curword]=true\n }\n return results\n} | 10 | 0 | [] | 3 |
word-ladder-ii | Run Time Analysis For Word Ladder II (Java) | run-time-analysis-for-word-ladder-ii-jav-7mqg | I tried at least 10 methods as well as read at least 10 articles and posts for this problem. I want to summarize what I found here.\n\nKey point to include comm | siyang3 | NORMAL | 2015-02-28T20:28:55+00:00 | 2015-02-28T20:28:55+00:00 | 1,858 | false | I tried at least 10 methods as well as read at least 10 articles and posts for this problem. I want to summarize what I found here.\n\n**Key point to include common word on two paths is to use a set to collect words for current layer and then delete the set from dict after finishing current layer.**\n\nMethods: \n\n(1) BFS to construct a parent->children map, DFS on the map (MLE).\n(2) BFS to construct a child->parents map, DFS on the map (600+ ms)\n(3) BFS to construct a level-by-level tree, DFS with backtrace on the tree (TLE).\n(4) BFS to construct a level-by-level tree (using List<String>) , DFS avoid backtrace on the tree (1800+ ms).\n(5) BFS to construct a level-by-level tree (using Set<String>) , DFS with backtrace on the tree (1400+ ms).\n(6) BFS to construct path (1000+ ms).\n\nMethod (2) is most efficient and was most widely used. But actually, I think if memory is big enough, method (1) will be likely to get same run time performance. Because these two methods use map to carry relationship.\n\nMethod(3),(4),(5) are my own solutions, it runs so slow because they use List<> to carry the relationship, which can not achieve O(1) visiting a given word.\n\nMethod(6) is unique. It doesn't need DFS. The relationship was stored on the path. \n\nTo sum up, since you always need to get a word's parent/children list/set, using a map can achieve O(1) run time, map beats other data structure in storing the relationship. \n\nAnd for memory use. Storing all the children for a word will always get MLE because a parent can have length*26 children while a child can only have at most 2 or 3 parents. Parent select children first!\n\nCodes:\n\nMethod(2):\n\n public class Solution { \n public List<List<String>> findLadders(String start, String end, Set<String> dict) { \n List<List<String>> rslt = new ArrayList<List<String>>(); \n Map<String, List<String>> parents = new HashMap<String, List<String>>(); \n boolean found = false; \n \n // initialize \n Set<String> cur_layer = new HashSet<String>(); \n cur_layer.add(start); \n if(dict.contains(start)) dict.remove(start); \n dict.add(end); \n \n // BFS construct map \n while(!found && !cur_layer.isEmpty()){ \n Set<String> new_layer = new HashSet<String>(); \n Iterator<String> iter = cur_layer.iterator(); \n while(iter.hasNext()){ \n String s = iter.next(); \n for(String t: neighbors(s, dict)){ \n new_layer.add(t); \n if(!parents.containsKey(t)){ \n List<String> list = new ArrayList<String>(); \n list.add(s); \n parents.put(t,list); \n }else{ \n List<String> list = parents.get(t); \n list.add(s); \n } \n if(t.equals(end)) found = true; \n } \n } \n dict.removeAll(new_layer); \n cur_layer = new_layer; \n } \n \n // DFS construct paths \n Stack<String> path = new Stack<String>(); \n path.push(end); \n dfs(start, end, path, parents, rslt); \n \n return rslt; \n } \n \n private void dfs(String start, String s, Stack<String> path, Map<String, List<String>> parents, List<List<String>> rslt){ \n // base case \n if(s.equals(start)){ \n List<String> list = new ArrayList<String>(); \n list.addAll(path); \n Collections.reverse(list); \n rslt.add(list); \n return; \n } \n // edge case \n if(!parents.containsKey(s)) return; \n // recursion \n for(String t: parents.get(s)){ \n path.push(t); \n dfs(start, t, path, parents, rslt); \n path.pop(); \n } \n } \n \n private List<String> neighbors(String s, Set<String> dict){ \n List<String> list = new ArrayList<String>(); \n char[] chars = s.toCharArray(); \n for(int j = 0;j < s.length();j++){ \n char original = chars[j]; \n for(char c = 'a';c <= 'z';c++){ \n chars[j] = c; \n String t = new String(chars); \n if(!t.equals(s) && dict.contains(t)) list.add(t); \n } \n chars[j] = original; \n } \n return list; \n } \n } \n\nMethod (6)\n\n public class Solution { \n public List<List<String>> findLadders(String start, String end, Set<String> dict) { \n List<List<String>> rslt = new ArrayList<List<String>>(); \n Deque<List<String>> paths = new LinkedList<List<String>>(); \n boolean found = false; \n \n // initialize path \n List<String> path = new ArrayList<String>(); \n path.add(start); \n paths.offerLast(path); \n \n // add end to dictionary, remove start from dict \n dict.add(end); \n if(dict.contains(start)) dict.remove(start); \n \n // BFS \n while(!found && !paths.isEmpty()){ \n Set<String> set = new HashSet<String>(); \n int k = paths.size(); \n for(int i = 0;i < k;i++){ \n List<String> list = paths.pollFirst(); \n String s = list.get(list.size()-1); \n for(String t : neighbors(s, dict)){ \n set.add(t); \n List<String> newList = new ArrayList<String>(list); \n newList.add(t); \n paths.offerLast(newList); \n if(t.equals(end)){ \n found = true; \n rslt.add(newList); \n } \n } \n } \n dict.removeAll(set); \n } \n return rslt; \n } \n \n private List<String> neighbors(String s, Set<String> dict){ \n List<String> list = new ArrayList<String>(); \n char[] chars = s.toCharArray(); \n for(int j = 0;j < s.length();j++){ \n char original = chars[j]; \n for(char c = 'a';c <= 'z';c++){ \n chars[j] = c; \n String t = new String(chars); \n if(dict.contains(t)) list.add(t); \n } \n chars[j] = original; \n } \n return list; \n } \n } | 10 | 0 | ['Breadth-First Search'] | 2 |
word-ladder-ii | Python solution in 578ms | python-solution-in-578ms-by-clue-3qk8 | The trick is use set to save the words at each level because different words could ladder to the same word. It was 2580ms using list.\n \n alphabet = se | clue | NORMAL | 2015-01-05T18:13:39+00:00 | 2018-08-29T23:37:06.653679+00:00 | 5,536 | false | The trick is use `set` to save the words at each level because different words could ladder to the same word. It was 2580ms using `list`.\n \n alphabet = set('abcdefghijklmnopqrstuvwxyz')\n def findLadders(self, start, end, dict):\n dict.add(end)\n level_tracker = collections.defaultdict(set)\n self.parents_tracker = {}\n last = {start}\n while last and end not in level_tracker:\n current = set([])\n level_tracker.clear()\n for word in last:\n for next_word in self.ladder(word, dict):\n if next_word not in self.parents_tracker:\n current.add(next_word)\n level_tracker[next_word].add(word)\n self.parents_tracker.update(level_tracker)\n last = current\n return [] if not last else self.generate_paths(start, end)\n \n def ladder(self, word, dict):\n for i in xrange(len(word)):\n for letter in self.alphabet - {word[i]}:\n new_word = word[:i] + letter + word[i + 1:]\n if new_word in dict:\n yield new_word\n \n def generate_paths(self, start, end):\n ret = [[end]]\n while ret[-1][0] != start:\n new_ret = []\n for path in ret:\n for parent in self.parents_tracker[path[0]]:\n new_ret.append([parent] + path)\n ret = new_ret\n return ret | 10 | 0 | ['Python'] | 6 |
word-ladder-ii | C++ - Guaranteed To Understand - BFS, Graph, No TLE - 44ms :) | c-guaranteed-to-understand-bfs-graph-no-6wm6a | Finally after a long time trying to understand so many of the codes here, I myself got to understand one code and get accepted.\n\nLet me break it down to you. | geekykant | NORMAL | 2022-08-15T13:02:25.509261+00:00 | 2022-08-15T16:55:13.416165+00:00 | 890 | false | Finally after a long time trying to understand so many of the codes here, I myself got to understand one code and get accepted.\n\nLet me break it down to you. It\'s easy to understand. No messy codes.\n\n**Method 1**: Naive Word Ladder-I continued (TLE) \u274C \n(32 / 35 test cases passed) - Best for interview explanation\n\n```cpp\nvector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wlist){\n vector<vector<string>> res;\n unordered_set<string> wl(begin(wlist), end(wlist));\n\n queue<vector<string>> paths;\n paths.push({beginWord});\n\t\n bool minDepthFound = false;\n while(!paths.empty()){\n int size = paths.size();\n\t\t\n\t\t// At each BFS level, we store the erased words to check them again only in same level.\n unordered_set<string> erasedWordsLevel;\n\t\t\n\t\t//If the best least level found, break\n if(minDepthFound) break;\n\n while(size--){\n vector<string> path = paths.front(); paths.pop();\n string lastString = path.back();\n \n\t\t\tfor(int i=0; i<lastString.size(); i++){\n string temp = lastString;\n for(char ch=\'a\'; ch <= \'z\'; ch++){\n temp[i] = ch;\n if(temp == lastString) continue;\n \n\t\t\t\t\t// The word can be in erasedWords at this level OR in original word list.\n\t\t\t\t\tif(wl.count(temp) || erasedWordsLevel.count(temp)){\n path.push_back(temp);\n if(temp == endWord){\n minDepthFound = true;\n res.push_back(path);\n }else{\n paths.push(path);\n wl.erase(temp);\n erasedWordsLevel.insert(temp);\n }\n path.pop_back();\n }\n }\n }\n }\n }\n return res;\n}\n```\n\nLets analyze why TLE in Method 1.\n* For each `path` in the `paths` queue, we were taking `path` string array, and appending next possible "**1-letter different word**". So there comes chances that "same words" originate at each of the bfs levels, so we keep finding the next path for the "same word" multiple times.\n* Keep in mind this TLE occurs in that node/word, even though its overall `path` is unique.\n\n**Method 2**: BFS, Build Graph and DFS \u2705 (It\'s easy, give it a read)\n\n* Instead of me trying to explain, watch this [video from TechDose](https://www.youtube.com/watch?v=mIZJIuMpI2M&ab_channel=TECHDOSE). \n* No one can teach you better. You will understand it < 15 mins. \n* Few code changes have to be made to pass the new LC testcases.\n\n**Changes made compared to video are:** \n* We are creating adjacency list in opposite direction. (**beginWord <-- endWord**)\n* Similarly, we DFS in the opposite direction from endWord to beginWord.\n* That\'s it.\n\nReason for taking the reverse direction is basically that will be incomplete-path nodes which is added on each level to the adjacency list. So no point of deep DFS on those nodes. \n\nConsider it like its difficult to find a node in a big tree from "parent->child", but its easier to find parent from "child->parent". (Thanks [@skate1512](https://leetcode.com/skate1512/))\n\n**BFS + DFS Code**\n```cpp\nvector<vector<string>> ans;\nunordered_map<string, unordered_set<string>> graph;\nunordered_map<string, int> visited;\n\nvector<string> path;\nvoid dfs(string& startWord, string& endWord){\n if(startWord == endWord){\n path.push_back(endWord);\n reverse(begin(path), end(path)); // store the answer after reversing\n ans.push_back(path);\n reverse(begin(path), end(path)); // reverse it back cuz backtracking\n path.pop_back();\n return;\n }\n\n path.push_back(startWord);\n for(string child: graph[startWord])\n dfs(child, endWord);\n path.pop_back();\n}\n\nvector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n unordered_set<string> wl(begin(wordList), end(wordList));\n if(!wl.count(endWord) || wl.empty()) return ans;\n\n\t// Visited array stores (string -> bfs level) information\n visited[beginWord] = 0; //level 0\n\n queue<string> q;\n q.push(beginWord);\n\n while(!q.empty()){\n string cur = q.front(); q.pop();\n for(int i=0; i < cur.size(); i++){\n string temp = cur;\n for(char ch=\'a\'; ch <= \'z\'; ch++){\n temp[i] = ch;\n if(temp == cur) continue;\n if(wl.count(temp)){\n\t\t\t\t\t// Unvisited node, simply add to adjacency list\n if(!visited.count(temp)){\n visited[temp] = 1 + visited[cur];\n graph[temp].insert(cur); // NOTE: beginWord <- endWord is the direction\n q.push(temp);\n }\n\t\t\t\t\t// direct child nodes check, if both child are at same level, add to adj list, else don\'t\n else if(visited[temp] == 1 + visited[cur])\n graph[temp].insert(cur); // NOTE: beginWord <- endWord is the direction\n }\n }\n }\n }\n\n\t// Reversely DFS from endWord to beginWord\n dfs(endWord, beginWord);\n return ans;\n}\n```\n\n**Upvote and let\'s learn from each others :)** | 9 | 0 | ['C'] | 3 |
word-ladder-ii | Finally a solution that does not gives TLE | PYTHON | DFS | finally-a-solution-that-does-not-gives-t-0cu9 | \nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n wordDict = defaultdict(set)\n | hhunterr | NORMAL | 2022-08-14T19:20:01.707318+00:00 | 2022-08-14T19:22:14.094364+00:00 | 445 | false | ```\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n wordDict = defaultdict(set)\n for word in wordList:\n if word != beginWord:\n for i in range(len(word)):\n wordDict[word[:i] + "*" + word[i+1:]].add(word)\n queue = deque([beginWord])\n visited = {beginWord: 1}\n parent_list = defaultdict(set)\n ans_path = []\n # print(wordDict)\n \n while queue:\n word = queue.popleft()\n if word == endWord: \n break\n for i in range(len(word)):\n for next_word in wordDict[word[:i] + "*" + word[i+1:]]:\n if next_word not in visited:\n visited[next_word] = visited[word] + 1\n queue.append(next_word)\n parent_list[next_word].add(word)\n elif visited[next_word] > visited[word]:\n parent_list[next_word].add(word)\n \n def dfs(word, path):\n if word == beginWord:\n ans_path.append(path[::-1])\n for next_word in parent_list[word]:\n dfs(next_word, path+[next_word])\n \n dfs(endWord, [endWord])\n return ans_path\n``` | 9 | 0 | ['Backtracking', 'Depth-First Search', 'Python'] | 1 |
word-ladder-ii | Python || Double BFS || Easy to understand | python-double-bfs-easy-to-understand-by-qsp1u | This solution implements BFS two times. One time from beginWord to endWord. And then from endWord to beginWord. The reason to use BFS two times is to avoid the | stevenhgs | NORMAL | 2022-08-14T13:53:37.164084+00:00 | 2022-08-15T07:42:48.905903+00:00 | 1,338 | false | This solution implements BFS two times. One time from `beginWord` to `endWord`. And then from `endWord` to `beginWord`. The **reason** to use BFS two times is to **avoid the memory limit** in the first BFS. In the first BFS a lot of useless paths would need to be kept in memory.\n\nThis solution works in 4 steps:\n1. The neighbor map is build for each word in wordList\n2. The first forward BFS is done starting from the beginWord until the endWord is reached. The connections are the connections build in the first step. During this step the reverse neighbor map is build.\n3. The second BFS is done starting from the endWord and using the reverse neighbor map. Here the paths from the endWord to beginWord are build.\n4. The paths build in step 3 need to be reversed. After reversing these paths this result is returned\n\n```\nfrom collections import defaultdict\n\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n # edge case\n if endWord not in wordList:\n return []\n \n # 1) build neighbor list for first bfs\n if beginWord not in wordList:\n wordList.append(beginWord)\n unseen = set(wordList)\n word_size = len(beginWord)\n neighbors = defaultdict(list)\n for word in wordList:\n for i in range(word_size):\n neighbors[f\'{word[:i]}*{word[i+1:]}\'].append(word)\n \n # 2) do first bfs and build reversed neighbors list for second bfs\n reverse_neighbors = defaultdict(list)\n n_t_h = [beginWord]\n unseen.remove(beginWord)\n while n_t_h:\n new_seen = set()\n for word in n_t_h:\n for i in range(word_size):\n for neighbor in neighbors[f\'{word[:i]}*{word[i+1:]}\']:\n if neighbor in unseen:\n reverse_neighbors[neighbor].append(word)\n new_seen.add(neighbor)\n n_t_h = list(new_seen)\n unseen -= new_seen\n if reverse_neighbors[endWord]:\n break\n \n # if endWord does not have reversed neigbors it is not reachable so return empty list\n if not reverse_neighbors[endWord]:\n return []\n \n # 3) do second bfs\n paths = [[endWord]]\n while True:\n new_paths = []\n for path in paths:\n last_node = path[-1]\n for reverse_neighbor in reverse_neighbors[last_node]:\n new_paths.append(path + [reverse_neighbor])\n paths = new_paths\n if paths[0][-1] == beginWord:\n break\n \n # 4) reverse the paths\n result = []\n for path in paths:\n path.reverse()\n result.append(path)\n return result\n\n``` | 9 | 0 | ['Breadth-First Search', 'Python', 'Python3'] | 1 |
word-ladder-ii | Java || Graph-BFS || Shortest Path || Image explanation | java-graph-bfs-shortest-path-image-expla-stlb | Approach:\nCreate a graph where indices of the words are the vertices of the graph and an edge exists between two vertices if those 2 words differ by a single l | yggins | NORMAL | 2022-08-14T10:50:56.041541+00:00 | 2022-08-14T10:50:56.041584+00:00 | 1,758 | false | Approach:\nCreate a graph where indices of the words are the vertices of the graph and an edge exists between two vertices if those 2 words differ by a single letter.\n\nConsider below input -\nInput: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]\n\nIn my code, beginWord has vertex 0 and words in wordList have vertices = (i+1), so for e.g. vertex of "hot" is 1 and that of "cog" is 6.\nThe graph for this input will look as shown in below image -\n\n\n\n\nIn above graph we can see the vertices and the corresponding words, the src is the beginWord and dest is the endWord. \nOur answer is **all the shortest paths between beginWord and endWord**.\nThose two paths are marked by orange and purple crosses in above image.\n0 -> 1 -> 2 -> 3 -> 6 i.e. ["hit","hot","dot","dog","cog"]\n0 -> 1 -> 4 -> 5 -> 6 i.e. ["hit","hot","lot","log","cog"]\n\n\nBelow is the Java code -\n\n```\nclass Solution {\n \n ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n List<List<Integer>> paths = new ArrayList<>();\n ArrayList<ArrayList<Integer>> parent = new ArrayList<>();\n \n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n int w = wordList.size();\n int i, j;\n \n for(i=0;i<w+1;i++){\n adj.add(new ArrayList<>());\n }\n \n for(i=0;i<w;i++){\n if(checkSingleDiff(beginWord, wordList.get(i)) == 1){\n addEdge(0, i+1);\n }\n }\n \n for(i=0;i<w;i++){\n for(j=i+1;j<w;j++){\n if(checkSingleDiff(wordList.get(i), wordList.get(j)) == 1){\n addEdge(i+1, j+1);\n }\n }\n }\n \n // System.out.println("ADJ is");\n // for(i=0;i<adj.size();i++){\n // System.out.print(i + " -> ");\n // ArrayList<Integer> temp = adj.get(i);\n // for(j=0;j<temp.size();j++){\n // System.out.print(temp.get(j) + " ");\n // }\n // System.out.println();\n // }\n \n int beginWordInd = 0;\n int endWordInd = -1;\n for(i=0;i<w;i++){\n if(wordList.get(i).equals(endWord)){\n endWordInd = i+1;\n break;\n }\n }\n \n List<List<String>> ans = new ArrayList<>();\n if(endWordInd != -1){ \n ans = getShortestSequences(beginWordInd, endWordInd, w+1, wordList, beginWord);\n }\n \n return ans;\n }\n \n private List<List<String>> getShortestSequences(int src, int dest, int vertices, List<String> wordList, String beginWord){\n ArrayList<Integer> path = new ArrayList<>();\n \n int i, j;\n for(i=0;i<vertices;i++){\n parent.add(new ArrayList<>());\n }\n \n BFS(vertices, src, wordList);\n \n getShortestSequencesUtil(path, vertices, dest);\n \n // System.out.println("Size of paths is " + paths.size());\n for(i=0;i<paths.size();i++){\n Collections.reverse(paths.get(i));\n paths.set(i, paths.get(i));\n }\n \n List<List<String>> ans = new ArrayList<>();\n \n for(i=0;i<paths.size();i++){\n List<Integer> p = paths.get(i);\n ArrayList<String> pp = new ArrayList<>();\n for(j=0;j<p.size();j++){\n if(p.get(j) == 0){\n pp.add(beginWord);\n }\n else{\n pp.add(wordList.get(p.get(j) - 1)); \n }\n }\n ans.add(pp);\n }\n \n return ans;\n }\n \n private void getShortestSequencesUtil(ArrayList<Integer> path, int vertices, int dest){\n if(dest == -1){\n paths.add(new ArrayList<>(path));\n return;\n }\n \n for(int p : parent.get(dest)){\n path.add(dest);\n getShortestSequencesUtil(path, vertices, p);\n path.remove(path.size() - 1);\n }\n }\n \n private void BFS(int vertices, int src, List<String> wordList){\n int shortestDist[] = new int[vertices];\n Arrays.fill(shortestDist, Integer.MAX_VALUE);\n \n Queue<Integer> q = new LinkedList<>();\n q.offer(src);\n parent.get(src).clear();\n parent.get(src).add(-1);\n shortestDist[src] = 0;\n \n while(q.isEmpty() == false){\n int u = q.poll();\n for(int v : adj.get(u)){\n if(shortestDist[u] + 1 < shortestDist[v]){\n shortestDist[v] = shortestDist[u] + 1;\n q.offer(v);\n parent.get(v).clear();\n parent.get(v).add(u);\n }\n else if(shortestDist[u] + 1 == shortestDist[v]){\n parent.get(v).add(u);\n }\n }\n }\n \n // System.out.println("Parent is ");\n // for(int i=0;i<parent.size();i++){\n // ArrayList<Integer> p = parent.get(i);\n // System.out.print(i + " -> ");\n // for(int j=0;j<p.size();j++){\n // System.out.print(p.get(j) + " "); \n // }\n // System.out.println();\n // }\n // System.out.println();\n \n // System.out.println("Shortest distance is ");\n // for(int i=0;i<shortestDist.length;i++){\n // System.out.print(shortestDist[i] + " ");\n // }\n // System.out.println();\n }\n \n private void addEdge(int u, int v){\n adj.get(u).add(v);\n adj.get(v).add(u);\n }\n \n private int checkSingleDiff(String a, String b){\n int i;\n int count = 0;\n for(i=0;i<a.length();i++){\n if(a.charAt(i) != b.charAt(i)){\n count++;\n }\n }\n \n return count;\n }\n}\n```\n\nYou can uncomment the comments to see the adjacency list, parent list and shortest distance array, it will be as follows -\n```\nADJ is\n0 -> 1 \n1 -> 0 2 4 \n2 -> 1 3 4 \n3 -> 2 5 6 \n4 -> 1 2 5 \n5 -> 3 4 6 \n6 -> 3 5 \nParent is \n0 -> -1 \n1 -> 0 \n2 -> 1 \n3 -> 2 \n4 -> 1 \n5 -> 4 \n6 -> 3 5 \n\nShortest distance is \n0 1 2 3 2 3 4 \nSize of paths is 2\n```\n\n\n*Kindly upvote if this solution has helped you.\nThanks for reading! :)* | 9 | 0 | ['Breadth-First Search', 'Java'] | 2 |
word-ladder-ii | JAVA || Clean & Concise & Optimal Code || Breadth First Search + Backtracking Technique | java-clean-concise-optimal-code-breadth-bmesk | \nclass Solution {\n \n Set<String> wordSet = new HashSet<> ();\n List<String> currPath = new ArrayList<> ();\n List<List<String>> shortestPath = ne | anii_agrawal | NORMAL | 2021-07-24T21:37:29.559630+00:00 | 2021-07-24T21:37:29.559670+00:00 | 865 | false | ```\nclass Solution {\n \n Set<String> wordSet = new HashSet<> ();\n List<String> currPath = new ArrayList<> ();\n List<List<String>> shortestPath = new ArrayList<> ();\n Map<String, List<String>> adjacencyList = new HashMap<> ();\n \n public List<String> findNeighbors (String currWord) {\n \n List<String> neighborsList = new ArrayList<> ();\n char[] letters = currWord.toCharArray ();\n \n for (int i = 0; i < letters.length; i++) {\n char letter = letters[i];\n \n for (char c = \'a\'; c <= \'z\'; c++) {\n letters[i] = c;\n String word = new String (letters);\n if (letter != c && wordSet.contains (word)) {\n neighborsList.add (word);\n }\n }\n \n letters[i] = letter;\n }\n \n return neighborsList;\n }\n \n public void bfs (String beginWord) {\n \n Queue<String> queue = new LinkedList<> ();\n queue.offer (beginWord);\n wordSet.remove (beginWord);\n \n while (!queue.isEmpty ()) {\n int size = queue.size ();\n Set<String> visitedSet = new HashSet<> ();\n \n while (size-- != 0) {\n String currWord = queue.poll ();\n List<String> neighborsList = findNeighbors (currWord);\n \n for (String word : neighborsList) {\n if (!adjacencyList.containsKey (currWord)) {\n adjacencyList.put (currWord, new ArrayList<> ());\n }\n \n adjacencyList.get (currWord).add (word);\n visitedSet.add (word);\n }\n }\n \n for (String word : visitedSet) {\n queue.offer (word);\n wordSet.remove (word);\n }\n }\n }\n \n public void backtrack (String beginWord, String endWord) {\n \n if (beginWord.equals (endWord)) {\n shortestPath.add (new ArrayList<> (currPath));\n return;\n }\n else if (!adjacencyList.containsKey (beginWord)) {\n return;\n }\n \n for (String word : adjacencyList.get (beginWord)) {\n currPath.add (word);\n backtrack (word, endWord);\n currPath.remove (word);\n }\n }\n \n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n \n for (String word : wordList) {\n wordSet.add (word);\n }\n \n if (!wordSet.contains (endWord)) {\n return shortestPath;\n }\n \n bfs (beginWord);\n currPath.add (beginWord);\n backtrack (beginWord, endWord);\n \n return shortestPath;\n }\n}\n```\n\nPlease help to **UPVOTE** if this post is useful for you.\nIf you have any questions, feel free to comment below.\n\n**LOVE CODING :)\nHAPPY CODING :)\nHAPPY LEARNING :)** | 9 | 0 | ['Backtracking', 'Breadth-First Search', 'Java'] | 0 |
word-ladder-ii | AC Python two-end BFS 124 ms | ac-python-two-end-bfs-124-ms-by-dietpeps-m8j1 | Two-end BFS to find the ladders and a recursive DFS to generate the answer\nidea is the same as word ladder i, [peaceful's solution][1]\n\n\n def _build(self | dietpepsi | NORMAL | 2015-10-14T05:40:55+00:00 | 2018-09-01T10:05:22.137536+00:00 | 4,733 | false | Two-end BFS to find the ladders and a recursive DFS to generate the answer\nidea is the same as word ladder i, [peaceful's solution][1]\n\n\n def _build(self, parent, path, paths):\n if not parent[path[-1]]:\n paths.append(path[:])\n return\n for nextWord in parent[path[-1]]:\n path.append(nextWord)\n self._build(parent, path, paths)\n path.pop()\n\n def buildLadders(self, aWord, bWord, beginWord, parent, ans):\n paths = [[], []]\n path = [aWord]\n self._build(parent, path, paths[0])\n path = [bWord]\n self._build(parent, path, paths[1])\n if paths[0][0][-1] != beginWord:\n paths.reverse()\n for path in paths[0]:\n path.reverse()\n for aPath in paths[0]:\n for bPath in paths[1]:\n ans.append(aPath + bPath)\n\n def findLadders(self, beginWord, endWord, wordList):\n fronts = [{beginWord}, {endWord}]\n parent = {beginWord: None, endWord: None}\n wordList.discard(beginWord)\n wordList.discard(endWord)\n ans = []\n while fronts[0] and fronts[1] and not ans:\n if len(fronts[0]) > len(fronts[1]):\n fronts.reverse()\n newLevel = set()\n for word in fronts[0]:\n for i in xrange(len(beginWord)):\n for char in string.lowercase:\n newWord = word[:i] + char + word[i + 1:]\n if newWord in fronts[1]:\n self.buildLadders(word, newWord, beginWord, parent, ans)\n if newWord in newLevel:\n parent[newWord].append(word)\n if newWord in wordList:\n newLevel.add(newWord)\n wordList.remove(newWord)\n parent[newWord] = [word]\n fronts[0] = newLevel\n return ans\n\n\n # 37 / 37 test cases passed.\n # Status: Accepted\n # Runtime: 124 ms\n # 98.60%\n\n\n [1]: https://leetcode.com/discuss/63927/python-solution-based-on-two-end-bfs-120ms | 9 | 0 | ['Python'] | 9 |
word-ladder-ii | 💥 300 streak days!💪🏻💪🏻💪🏻 | 300-streak-days-by-ft_hs1396-h72d | Hello Guys!\nI have been here for #300# consecutive days, in any mood, sad or happy, healthy or sick, free or busy. | ft_hs1396 | NORMAL | 2022-08-14T15:40:09.861547+00:00 | 2022-08-14T15:40:09.861582+00:00 | 187 | false | Hello Guys!\nI have been here for #300# consecutive days, in any mood, sad or happy, healthy or sick, free or busy. | 8 | 1 | [] | 1 |
word-ladder-ii | C++ || BFS and BackTracking || Faster || 30ms | c-bfs-and-backtracking-faster-30ms-by-me-ihzd | \nclass Solution {\npublic:\n unordered_set<string> dic;\n unordered_map<string,int> mp;\n vector<vector<string>> ans;\n void dfs(string ew,vector<string> | Meraki3000 | NORMAL | 2022-08-14T09:53:43.052462+00:00 | 2022-08-14T09:53:43.052490+00:00 | 1,704 | false | ```\nclass Solution {\npublic:\n unordered_set<string> dic;\n unordered_map<string,int> mp;\n vector<vector<string>> ans;\n void dfs(string ew,vector<string> &temp,string bw)\n {\n \n int curr=mp[ew];\n temp.push_back(ew);\n if(ew==bw)\n {\n reverse(temp.begin(),temp.end());\n ans.push_back(temp);\n reverse(temp.begin(),temp.end());\n temp.pop_back();\n return ;\n }\n for(int i=0;i<ew.size();i++)\n {\n string st=ew;\n for(char ch=\'a\';ch<=\'z\';ch++)\n {\n st[i]=ch;\n if(mp[st] and mp[st]==curr-1)\n { \n dfs(st,temp,bw);\n }\n }\n }\n temp.pop_back();\n \n }\n \n \n \n vector<vector<string>> findLadders(string bw, string ew, vector<string>& wl) {\n \n \n for(auto it:wl)dic.insert(it);\n queue<string> q;\n q.push(bw);\n mp[bw]++;\n while(!q.empty())\n {\n auto k=q.front();\n q.pop();\n int steps=mp[k]+1;\n for(int i=0;i<k.size();i++)\n {\n string temp=k;\n for(char ch=\'a\';ch<=\'z\';ch++)\n {\n temp[i]=ch;\n if(dic.count(temp) and !mp[temp])\n {\n mp[temp]=steps;\n q.push(temp);\n }\n }\n } \n }\n if(mp[ew])\n {\n vector<string> temp;\n dfs(ew,temp,bw); }\n return ans;\n \n }\n};\n``` | 8 | 1 | ['Backtracking', 'Depth-First Search', 'Breadth-First Search', 'C', 'C++'] | 1 |
word-ladder-ii | BFS + DFS + Memoization - Non-TLE solution | bfs-dfs-memoization-non-tle-solution-by-zb09j | \nclass Solution {\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n Set<String> dict = new HashSet | jainakshat425 | NORMAL | 2022-07-31T05:34:48.639587+00:00 | 2022-07-31T05:34:48.639642+00:00 | 1,056 | false | ```\nclass Solution {\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n Set<String> dict = new HashSet(wordList);\n if( !dict.contains(endWord) )\n return new ArrayList();\n \n // adjacent words for each word\n Map<String,List<String>> adjacency = new HashMap();\n Queue<String> queue = new LinkedList();\n // does path exist?\n boolean found = false;\n \n // BFS for shortest path, keep removing visited words\n queue.offer(beginWord);\n dict.remove(beginWord);\n \n while( !found && !queue.isEmpty() ) {\n int size = queue.size();\n // adjacent words in current level\n HashSet<String> explored = new HashSet();\n\n while( size-- > 0 ) {\n String word = queue.poll();\n \n if( adjacency.containsKey(word) )\n continue;\n \n // remove current word from dict, and search for adjacent words\n dict.remove(word);\n List<String> adjacents = getAdjacents(word, dict);\n adjacency.put(word, adjacents);\n\n for(String adj : adjacents) {\n if( !found && adj.equals(endWord) ) \n found = true;\n \n explored.add(adj);\n queue.offer(adj);\n }\n }\n // remove words explored in current level from dict\n for(String word : explored)\n dict.remove(word);\n }\n\n // if a path exist, dfs to find all the paths\n if( found ) \n return dfs(beginWord, endWord, adjacency, new HashMap());\n else\n return new ArrayList();\n }\n \n private List<String> getAdjacents(String word, Set<String> dict) {\n List<String> adjs = new ArrayList();\n char[] wordChars = word.toCharArray();\n \n for(int i=0; i<wordChars.length; i++) \n for(char c=\'a\'; c<=\'z\'; c++) {\n char temp = wordChars[i];\n wordChars[i] = c;\n \n String newAdj = new String(wordChars);\n if( dict.contains(newAdj) )\n adjs.add(newAdj);\n \n wordChars[i] = temp;\n }\n return adjs;\n }\n \n private List<List<String>> dfs(String src, String dest, \n Map<String,List<String>> adjacency, \n Map<String,List<List<String>>> memo) {\n if( memo.containsKey(src) )\n return memo.get(src);\n \n List<List<String>> paths = new ArrayList();\n \n\t\t// reached dest? return list with dest word\n if( src.equals( dest ) ) {\n paths.add( new ArrayList(){{ add(dest); }} );\n return paths;\n }\n\n\t\t// no adjacent for curr word? return empty list\n List<String> adjacents = adjacency.get(src);\n if( adjacents == null || adjacents.isEmpty() )\n return paths;\n\n for(String adj : adjacents) {\n List<List<String>> adjPaths = dfs(adj, dest, adjacency, memo);\n \n for(List<String> path : adjPaths) {\n if( path.isEmpty() ) continue;\n \n List<String> newPath = new ArrayList(){{ add(src); }};\n newPath.addAll(path);\n \n paths.add(newPath);\n }\n } \n memo.put(src, paths);\n return paths;\n }\n}\n``` | 8 | 0 | ['Java'] | 0 |
word-ladder-ii | ✅C++ Easy-To-Understand BFS solution | c-easy-to-understand-bfs-solution-by-igi-vca3 | \tclass Solution {\n\t\t vector> ans;\n\tpublic:\n\t\t void helper(string start,string end,unordered_set &st){\n\t\t\t queue> q;\n\t\t\t q.push({start}); //s | igi17 | NORMAL | 2022-02-26T10:56:04.858676+00:00 | 2022-02-26T10:56:04.858705+00:00 | 793 | false | \tclass Solution {\n\t\t vector<vector<string>> ans;\n\tpublic:\n\t\t void helper(string start,string end,unordered_set<string> &st){\n\t\t\t queue<vector<string>> q;\n\t\t\t q.push({start}); //storing path\n\t\t\t bool flag=false;\n\t\t\t while(!q.empty()){\n\t\t\t\t int n=q.size();\n\t\t\t\t while(n--)\n\t\t\t\t {\n\t\t\t\t\t vector<string> curr_path=q.front(); \n\t\t\t\t\t q.pop();\n\t\t\t\t\t if(curr_path.back()==end){\n\t\t\t\t\t\t ans.push_back(curr_path);\n\t\t\t\t\t\t flag=true; //if we got our answer then we need to consider\n\t\t\t\t\t\t\t// only this level of bfs\n\t\t\t\t\t\t continue;\n\t\t\t\t\t }\n\t\t\t\t\t string temp=curr_path.back();\n\t\t\t\t\t st.erase(temp);\n\t\t\t\t\t for(int j=0;j<temp.length();j++){\n\t\t\t\t\t\t\tstring curr=temp;\n\t\t\t\t\t\t for(int i=0;i<26;i++){\n\t\t\t\t\t\t\t curr[j]=i+\'a\';\n\t\t\t\t\t\t\t // cout<<curr<<" ";\n\t\t\t\t\t\t\t if(st.find(curr)!=st.end()){ \n\t\t\t\t\t\t\t\t curr_path.push_back(curr);\n\t\t\t\t\t\t\t\t q.push({curr_path});\n\t\t\t\t\t\t\t\t curr_path.pop_back();\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t }\n\t\t\t\t\t }\n\t\t\t\t }\n\t\t\t\t\t if(flag) break;\n\t\t\t }\n\t\t}\n\t\tvector<vector<string>> findLadders(string start, string end, vector<string>& wordList) {\n\t\t\t\t unordered_set<string> st;\n\t\t\t\t for(auto &it: wordList) st.insert(it);\n\n\t\t\t\t if(st.find(end)==st.end()) return {};\n\t\t\t\t helper(start,end,st);\n\t\t\t return ans;\n\t\t}\n\t}; | 8 | 0 | ['Breadth-First Search', 'C'] | 1 |
word-ladder-ii | Java| Clean Code | Easy to understand| Well Explained | java-clean-code-easy-to-understand-well-yqzm3 | My approach to solve this problem\n\nI created a adjacency list of the strings , i.e. next path of the string where it can got to with change of one char in fr | abhishekgoel | NORMAL | 2021-01-15T19:34:31.820255+00:00 | 2021-01-15T19:53:53.529752+00:00 | 1,769 | false | My approach to solve this problem\n\nI created a adjacency list of the strings , i.e. next path of the string where it can got to with change of one char in from the previous string. I did this by converting the string to a char array and then changing the character at each index of string from **a to z** . so if i have the string ```hit``` then i would replace h with characters **a to z** and then check if any of those strings are present in my given ```words```. I used ```HashSet <string> words``` to store the values of ```wordList``` so that searching of string can be optimized to O(n). After generating all of the ```ArrayList <String> ans``` for each string in ```wordList``` i pushed the ```ans``` into ```graph```. And this is what we get. \n```\nhit-> hot\nhot-> dot, lot\ndot-> lot, dog\nlot-> log\ndog-> log, cog\nlog-> cog\n```\nWe keep track of a variable called depth which gives us the minimum transformation it took to convert ```beginWord``` to ```endWord```\n\nAfter getting the adjacency list above i called DFS on it and traversed until my ```depth``` is equal to 0 and if i get my ```beginWord``` equal to ```endWord``` , i push the ```ans``` array into my ```res``` and return it. \n\n**Problem: TLE arrised. **\n\nSolution: I optimised my adjacency list to a optimal adjacency list\n\n\nIn the image above levels are written of each string , we add them accordingly. \n\n```\nhit-> hot\nhot-> dot, lot\ndot-> dog\nlot-> log\ndog-> cog\nlog-> cog\n```\n\nWe can do this by adding the strings that are only children and not the parent. i.e. strings that lie ahead of us and not the strings that are lesser than our ```level``` . \n\n# CODE\n\n```\nclass Solution {\n \n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n HashSet<String> words=new HashSet<>(wordList);\n if(!words.contains(endWord)) return new ArrayList<>();\n \n HashMap<String,ArrayList<String>> graph=new HashMap<>(); // to make adjacency list\n HashMap<String,Integer> vis=new HashMap<>(); // to keep count of level traversal of str\n LinkedList<String> que=new LinkedList<>();\n \n que.addLast(beginWord);\n int level=0; int depth=0;\n vis.put(beginWord,0); // level of intial word will be 0\n \n //create graph bfs\n while(!que.isEmpty()){\n int size=que.size();\n level++;\n while(size-->0){\n String s=que.removeFirst();\n if(s.equals(endWord)){\n if(depth==0) depth=level;\n continue;\n }\n ArrayList<String> arr=new ArrayList<>();\n char[] ch=new char[s.length()];\n \n for(int i=0;i<s.length();i++){\n ch=s.toCharArray();\n char c=ch[i];\n for(int j=0;j<26;j++){\n if(c==(char)(j+\'a\')) continue;\n ch[i]=(char)(j+\'a\');\n String str=String.valueOf(ch);\n if(words.contains(str)){\n if(vis.getOrDefault(str,10000)>=level){\n vis.put(str,level);\n arr.add(str);\n que.addLast(str);\n }\n }\n }\n }\n \n graph.put(s,arr);\n }\n }\n \n //dfs\n HashMap<String,Integer> v=new HashMap<>();\n ArrayList<String> ans=new ArrayList<>();\n ans.add(beginWord);\n List<List<String>> res=new ArrayList<>();\n dfs(beginWord,endWord,depth-1,graph,v,ans,res);\n \n return res;\n \n }\n \n public static void dfs(String beginWord, String endWord, int depth, HashMap<String,ArrayList<String>>graph,HashMap<String,Integer> v,ArrayList<String> ans , List<List<String>> res){\n \n if(depth==0){\n if(beginWord.equals(endWord)){\n ArrayList<String> base=new ArrayList<>(ans);\n res.add(base);\n }\n return;\n }\n //mark\n v.put(beginWord,1);\n for(String s: graph.get(beginWord)){\n if(v.getOrDefault(s,0)!=1){\n ans.add(s);\n dfs(s,endWord,depth-1,graph,v,ans,res);\n ans.remove(ans.size()-1);\n }\n }\n v.put(beginWord,0);\n return;\n }\n}\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n | 8 | 1 | ['Depth-First Search', 'Breadth-First Search', 'Graph', 'Java'] | 3 |
word-ladder-ii | Concise Swift Solution, with my understanding | concise-swift-solution-with-my-understan-0uaw | This is a question that asks to find the shortest paths between two nodes in a graph. First of all, if the endWord is not in the word list, then it means our gr | wds8807 | NORMAL | 2019-03-30T03:59:12.372617+00:00 | 2019-03-30T03:59:12.372660+00:00 | 364 | false | This is a question that asks to find the shortest paths between two nodes in a graph. First of all, if the ```endWord``` is not in the word list, then it means our graph does not contain ```endWord``` and we return ```[]```. \n\nAfter building the graph from the given word list, we can perform a breadth first search to find the shortest between the two given words. \n\nI use the "wild card" as the key of the dictionary but I think it\'s better to build an adjacency list by directly using the word itself as the key and its neighbors as values and I guess it will make it easier for us to traverse the graph.\n\nThen we use a standard BFS to find the shortest paths. The only thing to keep in mind is that the ```queue``` has the currently generated ```paths``` as elements. For example,\n\nAt first, our queue is ```[["hit"]]```.\nThen it becomes ```[["hit", "hot""]]```.\nAnd then it becomes ```[["hit", "hot", "dot"], ["hit", "hot", "lot"]]```, the reason being that every time we find another path, we create a new variable ```newPath``` locally with the value of the old path, append the new word to it, and append it (```newPath```) back to our ```queue```.\n\nOne of the most important thing is to keep in mind is, we should not insert the new word ```next``` to our visit history immediately, because it is also a possible candidate for the next ```path``` in our ```queue```. Therefore, we need to have a ```tmpVisit``` to store the visited node for the current queue, and a ```level``` variable to store current level, and union it with the visit history ```visited``` when we reach the next level (current path\'s length greater than current level). \n\nIn this way, we can find all shortest paths. Because when we union the ```tmpVisit``` with our visit history, we eliminate future visits to those words with longer paths.\n\nIf we have ```A -> B -> C``` and ```A -> D -> C```, then by doing things mentioned above we won\'t have something like ```A -> B -> E -> C```. In this way we can ensure from ```A``` to ```C``` we have the shortest pathes, which means if ```C``` is on the way to our destination, they the ```A -> B -> C``` and ```A -> D -> C``` ARE parts of our sortest paths to our destination.\n\nI know a bidirection BFS will be both faster and will consume less memory. But I\'ll move on for now.\n\nOne other thing I want to point out is don\'t get frustrated when you can\'t come up with a working solution within whataever amount of time, while seeing so many beautiful solutions in the discuss section. You don\'t know how many hours/days/weeks other folks have been struggling before they come up with their solutions. Just try your best and keep making faithful effort. One day you will reach where you want.\n\nCheers.\n\n```\nclass Solution {\n\t\n\t// Global vairable of dictionary\n\t// Key: wild card\n\t// Value: words that share same generic word\n\tvar dict: [String: [String]] = [:]\n\t\n\tfunc findLadders(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> [[String]] {\n\t\t\n\t\tguard wordList.contains(endWord) else { return [] }\n\t\t\n\t\t// Construct the dictionary\n\t\tfor word in wordList {\n\t\t\tfor(_, i) in word.indices.enumerated() {\n\t\t\t\tlet generic = String(word[..<i]) + "*" + String(word[word.index(after: i)...])\n\t\t\t\tdict[generic, default: []].append(word)\n\t\t\t}\n\t\t}\n\n\t\tvar queue: [[String]] = []\n\t\tvar visited: Set<String> = []\n\t\tvar currPath: [String] = []\n\t\tvar answer: [[String]] = []\n\t\t\n\t\tqueue.append([beginWord])\n\t\tvisited.insert(beginWord)\n\t\tcurrPath.append(beginWord)\n\t\t\n\t\tvar level = 1\n\t\tvar tmpVisits: [String] = []\n\t\t// BFS\n\t\twhile !queue.isEmpty {\n\t\t\tlet path = queue.removeFirst()\n\t\t\t\n\t\t\tif path.count > level {\n\t\t\t\tvisited.formUnion(tmpVisits)\n\t\t\t\ttmpVisits.removeAll()\n\t\t\t\tlevel += 1\n\t\t\t}\n\t\t\t\n\t\t\tguard let last = path.last else {\tcontinue }\n\t\t\t\n\t\t\tfor (_, i) in last.indices.enumerated() {\n\t\t\t\t\n\t\t\t\tlet generic = String(last[..<i] + "*" + last[last.index(after: i)...])\n\n\t\t\t\tguard let nexts = dict[generic] else {\n\t\t\t\t\tcontinue }\n\t\t\t\tfor next in nexts {\n\t\t\t\t\t\n\t\t\t\t\tguard !visited.contains(next) else { continue }\n\t\t\t\t\tvar newPath = path\n\t\t\t\t\tnewPath.append(next)\n\t\t\t\t\t//visited.insert(next)\n\t\t\t\t\ttmpVisits.append(next)\n\t\t\t\t\t\n\t\t\t\t\tif next == endWord {\n\t\t\t\t\t\tanswer.append(newPath)\n\t\t\t\t\t\tvisited.remove(next)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tqueue.append(newPath)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} // while !queue.isEmpty\n\t\t\n\t\treturn answer\n\t}\n}\n``` | 8 | 0 | [] | 1 |
word-ladder-ii | Word Ladder II [C++] | word-ladder-ii-c-by-moveeeax-z7hb | IntuitionThe problem requires finding the shortest transformation sequence(s) from beginWord to endWord, where each step can change only one character, and the | moveeeax | NORMAL | 2025-02-01T10:21:00.677630+00:00 | 2025-02-01T10:21:00.677630+00:00 | 1,440 | false | ### Intuition
The problem requires finding the shortest transformation sequence(s) from `beginWord` to `endWord`, where each step can change only one character, and the resulting word must exist in the `wordList`. Since we need the shortest sequences, we can use **Breadth-First Search (BFS)** to traverse level by level and build the transformation paths.
### Approach
1. **BFS for shortest paths:**
- Start from `beginWord`, exploring all possible one-letter transformations.
- Keep track of levels (depth) using a `levels` map to ensure we only expand the shortest paths.
- Store possible parents for each word using a `parents` map to later reconstruct the paths.
2. **Backtracking (DFS) for reconstructing paths:**
- Using the `parents` map, backtrack from `endWord` to `beginWord` to construct all possible shortest paths.
### Complexity
- **Time Complexity:**
- Constructing the adjacency list takes **\( O(NL^2) \)** where \( N \) is the number of words and \( L \) is the word length.
- BFS traversal is **\( O(NL) \)**.
- Backtracking is **\( O(k) \)** for constructing \( k \) shortest paths.
- **Overall: \( O(NL^2 + k) \)**.
- **Space Complexity:**
- **\( O(NL) \)** for storing parents and levels.
- **\( O(N) \)** for the queue.
- **Overall: \( O(NL) \)**.
### Code
```cpp
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordSet(wordList.begin(), wordList.end());
if (wordSet.find(endWord) == wordSet.end()) return {};
unordered_map<string, vector<string>> parents;
unordered_map<string, int> levels;
queue<string> q;
q.push(beginWord);
levels[beginWord] = 0;
int level = 0;
bool found = false;
while (!q.empty() && !found) {
int size = q.size();
unordered_map<string, vector<string>> newParents;
for (int i = 0; i < size; i++) {
string word = q.front();
q.pop();
string originalWord = word;
for (int j = 0; j < word.size(); j++) {
char originalChar = word[j];
for (char c = 'a'; c <= 'z'; c++) {
if (c == originalChar) continue;
word[j] = c;
if (wordSet.find(word) != wordSet.end()) {
if (levels.find(word) == levels.end() || levels[word] == level + 1) {
if (levels.find(word) == levels.end()) {
q.push(word);
levels[word] = level + 1;
}
newParents[word].push_back(originalWord);
}
}
}
word[j] = originalChar;
}
}
for (auto& p : newParents) {
parents[p.first].insert(parents[p.first].end(), p.second.begin(), p.second.end());
}
level++;
}
vector<vector<string>> results;
if (parents.find(endWord) == parents.end()) return results;
vector<string> path;
function<void(string)> dfs = [&](string word) {
path.push_back(word);
if (word == beginWord) {
results.push_back(vector<string>(path.rbegin(), path.rend()));
} else {
for (const string& parent : parents[word]) {
dfs(parent);
}
}
path.pop_back();
};
dfs(endWord);
return results;
}
};
``` | 7 | 0 | ['C++'] | 0 |
word-ladder-ii | 💥[EXPLAINED] TypeScript. Runtime beats 96.88% (TypeSript) | explained-typescript-runtime-beats-9688-e6etq | Intuition\nUse BFS to find shortest paths and distances and DFS to build all shortest paths from beginWord to endWord.\n\n# Approach\nUse BFS to calculate the s | r9n | NORMAL | 2024-08-23T01:58:13.160940+00:00 | 2024-08-26T19:51:26.335109+00:00 | 325 | false | # Intuition\nUse BFS to find shortest paths and distances and DFS to build all shortest paths from beginWord to endWord.\n\n# Approach\nUse BFS to calculate the shortest distances and track predecessors, and use DFS to reconstruct all paths from endWord to beginWord using the predecessors.\n\n# Complexity\n- Time complexity:\nO(N * 26^L), where N is the number of words in the wordList, and L is the length of each word. This accounts for generating neighbors and BFS traversal.\n\n- Space complexity:\n O(N * L), for storing distances, parents, and intermediate results.\n\n# Code\n```typescript []\nfunction findLadders(beginWord: string, endWord: string, wordList: string[]): string[][] {\n const wordSet = new Set(wordList);\n const result: string[][] = [];\n if (!wordSet.has(endWord)) return result;\n\n // Helper function to generate intermediate states\n function getNeighbors(word: string): string[] {\n const neighbors: string[] = [];\n for (let i = 0; i < word.length; i++) {\n const originalChar = word[i];\n for (let charCode = 97; charCode <= 122; charCode++) {\n const newChar = String.fromCharCode(charCode);\n if (newChar === originalChar) continue;\n const newWord = word.slice(0, i) + newChar + word.slice(i + 1);\n if (wordSet.has(newWord)) {\n neighbors.push(newWord);\n }\n }\n }\n return neighbors;\n }\n\n // BFS to find the shortest path lengths\n const distance = new Map<string, number>();\n const parents = new Map<string, string[]>();\n const queue: string[] = [beginWord];\n distance.set(beginWord, 0);\n parents.set(beginWord, []);\n \n while (queue.length) {\n const word = queue.shift()!;\n const currentDistance = distance.get(word)!;\n for (const neighbor of getNeighbors(word)) {\n if (!distance.has(neighbor)) {\n distance.set(neighbor, currentDistance + 1);\n queue.push(neighbor);\n parents.set(neighbor, [word]);\n } else if (distance.get(neighbor)! === currentDistance + 1) {\n (parents.get(neighbor) || []).push(word);\n }\n }\n }\n\n // DFS to collect all paths\n function dfs(word: string): string[][] {\n if (word === beginWord) return [[beginWord]];\n const paths: string[][] = [];\n const parentWords = parents.get(word) || [];\n for (const parent of parentWords) {\n for (const path of dfs(parent)) {\n paths.push([...path, word]);\n }\n }\n return paths;\n }\n\n return dfs(endWord);\n}\n\n``` | 7 | 0 | ['TypeScript'] | 0 |
word-ladder-ii | 126: with step by step explanation | 126-with-step-by-step-explanation-by-mar-oqg6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nSure, here\'s a step-by-step explanation of the code: \n\nclass Solution: | Marlen09 | NORMAL | 2023-02-18T06:40:28.134610+00:00 | 2023-02-18T06:51:20.773631+00:00 | 1,424 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSure, here\'s a step-by-step explanation of the code: \n```\nclass Solution:\n\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\n```\nThe function findLadders takes in a beginWord and endWord string, and a wordList list of strings, and returns a list of lists of strings, which represent the possible transformation sequences from the beginWord to endWord.\n```\nd = defaultdict(list)\nfor word in wordList:\n\tfor i in range(len(word)):\n\t\td[word[:i]+"*"+word[i+1:]].append(word)\n\n```\nA defaultdict d is created, which will be used to store a mapping from each "intermediate word" (words that can be obtained from the original word by changing one letter) to a list of words that can be formed from it. The for-loop iterates over each word in the wordList, and for each word, it replaces each letter of the word with a * character, one at a time, and stores the resulting intermediate word as a key in the d dictionary, with the original word as a value in the corresponding list.\n\n```\nif endWord not in wordList:\n\treturn []\n\n```\nIf the endWord is not present in the wordList, then no transformation sequence is possible, so an empty list is returned.\n```\nvisited1 = defaultdict(list)\nq1 = deque([beginWord])\nvisited1[beginWord] = []\n\nvisited2 = defaultdict(list)\nq2 = deque([endWord])\nvisited2[endWord] = []\n\nans = []\n\n```\nTwo defaultdicts visited1 and visited2 are created to store the visited nodes during BFS. Two deques q1 and q2 are initialized with the beginWord and endWord, respectively, and the visited nodes for beginWord and endWord are initialized as empty lists. ans is also initialized as an empty list, which will be used to store the transformation sequences.\n```\ndef dfs(v, visited, path, paths):\n\tpath.append(v)\n\tif not visited[v]:\n\t\tif visited is visited1:\n\t\t\tpaths.append(path[::-1])\n\t\telse:\n\t\t\tpaths.append(path[:])\n\tfor u in visited[v]:\n\t\tdfs(u, visited, path, paths)\n\tpath.pop()\n\n```\nA depth-first search (DFS) function is defined to find all possible transformation sequences between beginWord and endWord. The function takes in a v node, the visited dictionary, a path list, and a paths list, which will be used to store the transformation sequences found. If v is not visited, the current path list is added to paths list, with the path being reversed if visited is visited1. Then, for each adjacent node u of v (i.e., a word that can be formed from v by changing one letter), the dfs function is called recursively.\n```\ndef bfs(q, visited1, visited2, frombegin):\n\tlevel_visited = defaultdict(list)\n\tfor _ in range(len(q)):\n\t\tu = q.popleft()\n\n\t\tfor i in range(len(u)):\n\t\t\tfor v in d[u[:i]+"*"+u[i+1:]]:\n\t\t\t\tif v in visited2:\n\t\t\t\t\tpaths1 = []\n\t\t\t\t\tpaths2 = []\n\t\t\t\t\tdfs(u, visited1, [], paths1)\n\t\t\t\t\tdfs(v, visited2, [], paths2)\n\t\t\t\t\tif not frombegin:\n\t\t\t\t\t\t\n\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\td = defaultdict(list)\n\t\tfor word in wordList:\n\t\t\tfor i in range(len(word)):\n\t\t\t\td[word[:i]+"*"+word[i+1:]].append(word)\n\n\t\tif endWord not in wordList:\n\t\t\treturn []\n\n\t\tvisited1 = defaultdict(list)\n\t\tq1 = deque([beginWord])\n\t\tvisited1[beginWord] = []\n\n\t\tvisited2 = defaultdict(list)\n\t\tq2 = deque([endWord])\n\t\tvisited2[endWord] = []\n\n\t\tans = []\n\t\tdef dfs(v, visited, path, paths):\n\t\t\tpath.append(v)\n\t\t\tif not visited[v]:\n\t\t\t\tif visited is visited1:\n\t\t\t\t\tpaths.append(path[::-1])\n\t\t\t\telse:\n\t\t\t\t\tpaths.append(path[:])\n\t\t\tfor u in visited[v]:\n\t\t\t\tdfs(u, visited, path, paths)\n\t\t\tpath.pop()\n\n\t\tdef bfs(q, visited1, visited2, frombegin):\n\t\t\tlevel_visited = defaultdict(list)\n\t\t\tfor _ in range(len(q)):\n\t\t\t\tu = q.popleft()\n\n\t\t\t\tfor i in range(len(u)):\n\t\t\t\t\tfor v in d[u[:i]+"*"+u[i+1:]]:\n\t\t\t\t\t\tif v in visited2:\n\t\t\t\t\t\t\tpaths1 = []\n\t\t\t\t\t\t\tpaths2 = []\n\t\t\t\t\t\t\tdfs(u, visited1, [], paths1)\n\t\t\t\t\t\t\tdfs(v, visited2, [], paths2)\n\t\t\t\t\t\t\tif not frombegin:\n\t\t\t\t\t\t\t\tpaths1, paths2 = paths2, paths1\n\t\t\t\t\t\t\tfor a in paths1:\n\t\t\t\t\t\t\t\tfor b in paths2:\n\t\t\t\t\t\t\t\t\tans.append(a+b)\n\t\t\t\t\t\telif v not in visited1:\n\t\t\t\t\t\t\tif v not in level_visited:\n\t\t\t\t\t\t\t\tq.append(v)\n\t\t\t\t\t\t\tlevel_visited[v].append(u)\n\t\t\tvisited1.update(level_visited)\n\n\t\twhile q1 and q2 and not ans:\n\t\t\tif len(q1) <= len(q2):\n\t\t\t\tbfs(q1, visited1, visited2, True)\n\t\t\telse:\n\t\t\t\tbfs(q2, visited2, visited1, False)\n\n\t\treturn ans\n\t\t\t\n\t\t\t\n``` | 7 | 1 | ['Hash Table', 'String', 'Breadth-First Search', 'Python', 'Python3'] | 0 |
word-ladder-ii | Python faster than 95% BFS + DFS | python-faster-than-95-bfs-dfs-by-easy_pr-xl9w | Trick way to get all neighbors of all words in wordList in O(NK) time complexity, where N = len(wordList) and K = len(beginWord).\n\n\nclass Solution: \n | easy_problems_hunter | NORMAL | 2022-09-09T21:20:57.107314+00:00 | 2022-09-09T21:20:57.107358+00:00 | 453 | false | Trick way to get all neighbors of all words in wordList in O(NK) time complexity, where N = len(wordList) and K = len(beginWord).\n\n```\nclass Solution: \n \n def backtrack(self, curr_trans, curr_word):\n if curr_word == self.beginWord:\n curr_trans.append(curr_word)\n curr_trans.reverse()\n self.result.append(curr_trans)\n return\n \n for prev_word in self.prev[curr_word]:\n self.backtrack(curr_trans+[curr_word], prev_word)\n \n \n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n \n # Edge case:\n if endWord not in wordList:\n return []\n \n \n # 0. some init\n self.beginWord = beginWord\n L = len(beginWord)\n \n \n # 1. build adjacency map\n self.neighbors = collections.defaultdict(list)\n for i in range(L):\n for word in wordList:\n self.neighbors[word[:i] + \'*\' + word[i+1:]].append(word)\n \n \n # 2. Start BFS.\n # Define several datastructures:\n self.word_depth = dict.fromkeys(wordList, -1) # -1 depth means unvisited\n self.prev = collections.defaultdict(list) # storage all prev words 1 level higher than curernt word\n q = []\n q.append(beginWord)\n self.word_depth[beginWord] = 0\n \n while len(q) != 0:\n curr_word = q.pop(0)\n for i in range(L):\n for neighbor in self.neighbors[curr_word[:i] + \'*\' + curr_word[i+1:]]:\n # if not visited before:\n # 1. update with smallest depth\n # 2. add curr_word to its prev words\n # 3. add neighbor to q\n if self.word_depth[neighbor] == -1:\n self.word_depth[neighbor] = self.word_depth[curr_word] + 1\n self.prev[neighbor].append(curr_word)\n q.append(neighbor)\n else:\n # if visited before, if curr_word has same depth as its exisitng prev word, append to it. Ow ignore. \n if self.word_depth[neighbor] == self.word_depth[curr_word] + 1:\n self.prev[neighbor].append(curr_word)\n \n # 3. get all shortest transformation. Assume endWord can be reached from beginWord\n self.result = [] \n self.backtrack([], endWord)\n return self.result\n``` | 7 | 0 | ['Breadth-First Search'] | 1 |
word-ladder-ii | Best and most optimal C++ solution with complete explaination working code without TLE | best-and-most-optimal-c-solution-with-co-gj61 | Intuition\n\nThe Word Ladder II problem requires finding all the shortest transformation sequences from a start word to an end word, where each intermediate wor | mohitjaisal | NORMAL | 2022-08-23T08:46:23.130414+00:00 | 2024-07-27T12:56:25.805112+00:00 | 306 | false | ## Intuition\n\nThe Word Ladder II problem requires finding all the shortest transformation sequences from a start word to an end word, where each intermediate word must exist in a given word list, and each transformation can change only one letter. The problem can be broken down into two main tasks:\n1. **Building the Graph**: Representing words as nodes and transformations as edges.\n2. **Finding All Shortest Paths**: Using BFS to determine the shortest paths and DFS to enumerate all possible paths.\n\nThe intuition behind the solution is to treat the problem as a graph traversal problem where words are nodes, and edges exist between words that differ by exactly one character. Using BFS ensures that we find the shortest path, and DFS helps in backtracking to list all such paths.\n\n## Approach\n\n### Detailed Explanation\n\n1. **Graph Construction**:\n - Treat each word as a node.\n - Connect nodes (words) with an edge if they differ by exactly one character. This is determined by the `isNeighbor` function.\n\n2. **BFS for Shortest Path**:\n - Use BFS starting from the `beginWord` to find the shortest path distances to the `endWord`.\n - Maintain a parent list to record all possible predecessors of each word along the shortest paths.\n\n3. **DFS for Path Reconstruction**:\n - Use DFS to backtrack from the `endWord` to the `beginWord` using the parent information collected during BFS.\n - Collect all valid paths during this traversal.\n\n### Step-by-Step Process:\n\n1. **Neighbor Check**:\n - The `isNeighbor` function checks if two words are adjacent (differ by exactly one character).\n\n2. **BFS Traversal**:\n - Initialize distances and parent lists.\n - Traverse the graph using BFS to calculate the shortest distance from the start word to all other words and maintain parent nodes to reconstruct paths later.\n\n3. **DFS Backtracking**:\n - Perform DFS from the `endWord` to the `beginWord`, using the parent information from the BFS step to collect all shortest paths.\n\n## Complexity\n\n### Time Complexity:\n- **Graph Construction**: O(N^2 * M), where N is the number of words and M is the length of each word.\n- **BFS Traversal**: O(N + E), where N is the number of words and E is the number of edges.\n- **DFS Backtracking**: O(N * 2^L), where L is the length of the shortest path (in the worst case, each node could have two parents).\n\n### Space Complexity:\n- **Graph Storage**: O(N^2), for storing adjacency lists.\n- **BFS and DFS Structures**: O(N), for distance, parent, and path storage.\n\n## Code\n\n\n```C++ []\nclass Solution {\npublic:\n\n// Check if two strings are neighbors by counting differing characters\nbool isNeighbour(string &s1, string &s2) {\n int n = s1.length(), diff = 0;\n for (int i = 0; i < n; ++i)\n if (s1[i] != s2[i])\n diff++;\n return diff == 1;\n}\n\n// Perform BFS to find shortest paths from src to all nodes\nvoid BFS(int src, vector<vector<int>>& graph, vector<vector<int>>& parent, int n) {\n vector<int> dist(n, 1e9);\n dist[src] = 0;\n parent[src].push_back(-1);\n queue<int> q;\n q.push(src);\n\n while (!q.empty()) {\n int node = q.front();\n q.pop();\n for (int nbr : graph[node]) {\n if (dist[nbr] > dist[node] + 1) {\n dist[nbr] = dist[node] + 1;\n q.push(nbr);\n parent[nbr].clear();\n parent[nbr].push_back(node);\n } else if (dist[nbr] == dist[node] + 1) {\n parent[nbr].push_back(node);\n }\n }\n }\n}\n\n// Perform DFS to collect all paths from src to dest\nvoid DFS(int node, vector<vector<int>>& parent, vector<int>& path, vector<vector<int>>& allpath) {\n if (node == -1) {\n allpath.push_back(path);\n return;\n }\n for (int par : parent[node]) {\n path.push_back(par);\n DFS(par, parent, path, allpath);\n path.pop_back();\n }\n}\n\nvector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n int src = -1, dest = -1, n = wordList.size();\n for (int i = 0; i < n; ++i) {\n if (wordList[i] == beginWord) src = i;\n if (wordList[i] == endWord) dest = i;\n }\n\n vector<vector<string>> ans;\n if (dest == -1) return ans;\n if (src == -1) {\n wordList.push_back(beginWord);\n src = n++;\n }\n\n vector<vector<int>> parent(n);\n vector<vector<int>> graph(n);\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n if (isNeighbour(wordList[i], wordList[j])) {\n graph[i].push_back(j);\n graph[j].push_back(i);\n }\n }\n }\n\n BFS(src, graph, parent, n);\n vector<int> path;\n vector<vector<int>> allpath;\n DFS(dest, parent, path, allpath);\n\n for (auto& paths : allpath) {\n vector<string> current_path;\n for (int i = paths.size() - 2; i >= 0; --i) {\n current_path.push_back(wordList[paths[i]]);\n }\n current_path.push_back(endWord);\n ans.push_back(current_path);\n }\n return ans;\n}\n};\n | 7 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Graph', 'C++', 'Java'] | 2 |
word-ladder-ii | Analyze why we should DFS from endWord to avoid TLE | analyze-why-we-should-dfs-from-endword-t-6rsp | I thought it\'s a graph problem so I solved it this way:\n1. Build a graph by connecting words that differ by exactly 1 character\n2. Run a BFS from beginWord t | sc420 | NORMAL | 2022-08-14T14:33:17.158816+00:00 | 2022-08-15T02:36:53.330868+00:00 | 932 | false | I thought it\'s a graph problem so I solved it this way:\n1. Build a graph by connecting words that differ by exactly 1 character\n2. Run a BFS from `beginWord` to `endWord` to find the shortest distance\n3. Run a DFS from `beginWord` to `endWord`, ignoring any node that BFS didn\'t visit, and use backtracking technique to output each possible shortest path\n\nBut then I got TLE with a fairly small testcase, the first hunch the came to me is that we should run the DFS from `endWord` instead, but I still wasn\'t quite sure why. After my code got accepted, I was so curious that I wanted to draw the graph with the testcase that I failed to see what happened. After drawing the graph with GraphViz (see the comment for the rendering code), I immediately spotted the issue, let me draw an example to illustrate it:\n\n\n\nWe can see that running DFS from `beginWord` would waste lots of time exploring paths with dead ends in the `distance=3` nodes that BFS has visited, since BFS knows the shortest distance is 4 and we would limit the path to have at most 5 nodes in them. But running DFS from `endWord` would get all the paths if we just check if the connected node has been visited with the corresponding distance in the BFS process (e.g., `cab` is connected to `cat` but it\'s not what we\'re looking for) It\'s also why [some solution](https://leetcode.com/problems/word-ladder-ii/discuss/2421786/C%2B%2B-using-BFS-and-Backtracking-oror-NO-TLE-August2022) visits the parent nodes backward from `endWord`.\n\nMy solution is similar but doesn\'t require the parent-child relationship, I simply record what nodes are visited during the BFS process, and find the path from `endWord` only if the next node I\'m trying to add to the path has the distance of exactly previous distance minus 1 (the blue container in the above image). For example, when building path from `cat` of `distance=3`, `cat` is connected to `zat`, `cot` and `cab`, but only `zat` has a `distance=2`, so I would only add `zat` to the path and start from there in the next iteration.\n\nHere\'s my C++ solution that may not be as clean and concise as others, but I guess it\'s more memory-efficient (less than 88%) since I only use integers to build the graph as well as recoding the visited nodes in each distance.\n\n```cpp\nclass Solution {\npublic:\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n endWordIndex = findWordIndex(endWord, wordList);\n if (endWordIndex == -1) return {};\n // Add beginWord as the last node if it doesn\'t exist in wordList\n beginWordIndex = findWordIndex(beginWord, wordList);\n if (beginWordIndex == -1) {\n wordList.push_back(beginWord);\n beginWordIndex = wordList.size() - 1;\n }\n distances.assign(wordList.size(), -1);\n \n buildGraph(wordList);\n const int shortestDist = findShortestDistFromBeginToEndWord();\n if (shortestDist == -1) return {};\n \n findAllPaths(shortestDist, wordList);\n return results;\n }\n \n void buildGraph(const vector<string> &wordList) {\n nodeToNeighbors.assign(wordList.size(), {});\n for (int i = 0; i < wordList.size(); i++) {\n for (int j = 0; j < wordList.size(); j++) {\n if (i == j) continue;\n if (isConnected(wordList[i], wordList[j])) {\n nodeToNeighbors[i].push_back(j);\n }\n }\n }\n }\n \n int findShortestDistFromBeginToEndWord() {\n vector<int> visited(nodeToNeighbors.size(), false);\n visited[beginWordIndex] = true;\n deque<int> pending = {beginWordIndex};\n int distance = 0;\n while (!pending.empty()) {\n const int pendingSize = pending.size();\n for (int i = 0; i < pendingSize; i++) {\n const int node = pending.front();\n pending.pop_front();\n \n distances[node] = distance;\n if (node == endWordIndex) {\n return distance;\n }\n \n const auto &neighbors = nodeToNeighbors[node];\n for (const int neighbor : neighbors) {\n if (visited[neighbor]) continue;\n \n visited[neighbor] = true;\n pending.push_back(neighbor);\n }\n }\n distance++;\n }\n return -1;\n }\n \n void findAllPaths(const int shortestDist, const vector<string> &wordList) {\n vector<string> curPath(shortestDist + 1);\n findAllPathsRecursive(endWordIndex, shortestDist, shortestDist, wordList, curPath);\n }\n \n void findAllPathsRecursive(const int node, const int curDist, const int shortestDist, const vector<string> &wordList, vector<string> &curPath) {\n curPath[curDist] = wordList[node];\n if (curDist <= 0) {\n if (node == beginWordIndex) {\n results.push_back(curPath);\n }\n return;\n }\n \n const auto &neighbors = nodeToNeighbors[node];\n for (const int neighbor : neighbors) {\n if (distances[neighbor] != curDist - 1) continue;\n \n findAllPathsRecursive(neighbor, curDist - 1, shortestDist, wordList, curPath);\n }\n }\n \n int findWordIndex(const string &findWord, const vector<string> &wordList) {\n for (int i = 0; i < wordList.size(); i++) {\n if (wordList[i] == findWord) return i;\n }\n return -1;\n }\n \n bool isConnected(const string &s1, const string &s2) {\n int diffCount = 0;\n for (int i = 0; i < s1.length(); i++) {\n if (s1[i] != s2[i]) diffCount++;\n if (diffCount >= 2) return false;\n }\n return diffCount == 1;\n }\n \n int beginWordIndex = -1;\n int endWordIndex = -1;\n vector<vector<int>> nodeToNeighbors;\n vector<int> distances;\n vector<vector<string>> results;\n};\n``` | 7 | 0 | ['C', 'C++'] | 3 |
word-ladder-ii | C++✅ || Easy || Solution || BFS | c-easy-solution-bfs-by-prinzeop-lgpo | \nclass Solution {\npublic:\n\t\n\t// If s1 and s2 string only differ by single character\n\tbool canBeNext(string s1, string s2){\n\t\tint uncmn=0;\n\t\tfor(in | casperZz | NORMAL | 2022-08-14T11:38:38.280035+00:00 | 2022-08-14T11:38:38.280077+00:00 | 1,875 | false | ```\nclass Solution {\npublic:\n\t\n\t// If s1 and s2 string only differ by single character\n\tbool canBeNext(string s1, string s2){\n\t\tint uncmn=0;\n\t\tfor(int i=0; i<s1.size(); i++)\n\t\t\tuncmn += (s1[i] != s2[i]);\n\n\t\treturn uncmn==1;\n\t}\n\t\n\t// BFS to find the shortest paths first (Since BFS traverses nearest nodes first)\n\tvoid bfs(vector<vector<int>>& graph, vector<int> parent[], int n, int start, int end){\n\t\tvector<int> dist(n, 501); // Distance from parent node set to 501 i.e INF for all the nodes\n\t\t\n\t\t// Initializing queue for BFS with adding start node\n\t\tqueue<int> q; \n\t\tq.push(start);\n\n\t\tdist[start] = 0; // 0 for start node (Since start can reach to start my making 0 moves)\n\t\tparent[start] = {-1}; // no parent of start therefore marked -1\n\n\t\twhile(!q.empty()){\n\t\t\t// Fetching front element of queue\n\t\t\tint curr = q.front();\n\t\t\tq.pop();\n\t\t\t\n\t\t\t// Traversing all the connected elements of curr (Here nearest(convertable) words indexes)\n\t\t\tfor( int node: graph[curr]){\n\t\t\t\tif(dist[node] > dist[curr]+1){ // if marked distance is more than possible distance i.e, found nearest node (here word) \n\t\t\t\t\tdist[node] = dist[curr]+1;\n\t\t\t\t\tq.push(node);\n\t\t\t\t\tparent[node].clear(); // Removing previously calculated distant than current word\n\t\t\t\t\tparent[node].push_back(curr); // adding current word index\n\t\t\t\t}else if(dist[node] == dist[curr]+1) // if node(next word) is just one move ahead the current \n\t\t\t\t\tparent[node].push_back(curr);\n\t\t\t}\n\t\t}\n\n\t}\n\t\n\t// All the paths in the form of indexes of words from wordList\n\tvoid shortestPaths(int node, vector<vector<int>>& Paths, vector<int>& curr_path, vector<int> parent[]){\n\t\tif(node == -1){ // Reached parent of all(Baap of all !!)\n\t\t\tPaths.push_back(curr_path);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// Traversing parents of "node" i.e, words that can be reached from current word given the condition\n\t\tfor(int p: parent[node]){ \n\t\t\tcurr_path.push_back(p);\n\t\t\tshortestPaths(p, Paths, curr_path, parent);\n\t\t\tcurr_path.pop_back();\n\t\t}\n\t}\n\n\tvector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n\t\t// Indexes of beginWord and endWord respectively in wordList\n\t\tint start=-1, end=-1;\n\n\t\tfor(int i=0; i<wordList.size(); i++){\n\t\t\tif(wordList[i] == beginWord)\n\t\t\t\tstart = i;\n\t\t\tif(wordList[i] == endWord)\n\t\t\t\tend = i;\n\t\t}\n\n\t\tif(end == -1)\n\t\t\treturn {};\n\n\t\tif(start == -1){\n\t\t\twordList.emplace(wordList.begin(), beginWord); // setting beginWord as 1st element of wordList\n\t\t\tstart = 0;\n\t\t\tend++;\n\t\t}\n\n\t\tint n = wordList.size();\n\t\tvector<vector<int>> graph(n, vector<int>());\n\n\t\t// Creating adjency list for each pair of words that can be next i.e, word with only one uncommon char from current word\n\t\tfor(int i=0; i<n; i++){\n\t\t\tfor(int j=i+1; j<n; j++){\n\t\t\t\tif(canBeNext(wordList[i], wordList[j])){\n\t\t\t\t\tgraph[i].push_back(j);\n\t\t\t\t\tgraph[j].push_back(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Apply BFS to get a list of parent of word as index \n\t\tvector<int> parent[n];\n\t\tbfs(graph, parent, n, start, end);\n\n\t\t// Backtrack to find shortest paths from node to parent(endWord to beginWord) using indexes\n\t\tvector<vector<int>> Paths;\n\t\tvector<int> curr_path;\n\t\tshortestPaths(end, Paths, curr_path, parent);\n\n\t\t// Traverse through all shortest paths calculated and convert it into list of words(required answer)\n\t\tvector<vector<string>> ans;\n\n\t\tfor(auto path: Paths){\n\t\t\tvector<string> curr;\n\n\t\t\tfor(int i=0; i<path.size()-1; i++)\n\t\t\t\tcurr.push_back(wordList[path[i]]);\n\t\t\t\n\t\t\t// Since we started with endWord to reach beginWord we have to reverse the current order and add endWord\n\t\t\treverse(curr.begin(), curr.end()); \n\t\t\tcurr.push_back(wordList[end]);\n\t\t\tans.push_back(curr);\n\t\t}\n\n\t\treturn ans;\n\t}\n};\n``` | 7 | 0 | ['Breadth-First Search', 'C'] | 1 |
word-ladder-ii | Accepted Java Solution (24ms) | accepted-java-solution-24ms-by-mayank_oo-jb4b | Accepted Java Solution \n1. First we find the shortest path \'X\' between end word and start word \n2. Then we apply dfs from begin word and once we reach at X | Mayank_OO7 | NORMAL | 2022-08-14T06:20:03.915218+00:00 | 2022-08-14T07:34:19.631839+00:00 | 1,386 | false | # Accepted Java Solution \n1. First we find the shortest path \'X\' between end word and start word \n2. Then we apply dfs from begin word and once we reach at X \n* If we find the end word we push the current path in ans \n* Else we backtrack and try another path.\n```\nclass Solution {\n Set<String> set = new HashSet();\n String beginWord, endWord;\n Map<String, Integer> dist = new HashMap();\n List<List<String>> res;\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n this.beginWord = beginWord;\n this.endWord = endWord;\n this.res = new ArrayList();\n for (String word : wordList) {\n set.add(word);\n }\n short_path();\n if (dist.get(endWord) == null) return res;\n List<String> path = new ArrayList();\n path.add(endWord);\n dfs(endWord, path);\n return res;\n }\n \n private void short_path() {\n Queue<String> q = new LinkedList();\n q.offer(beginWord);\n dist.put(beginWord, 0);\n while(q.size() > 0) {\n String cur = q.poll();\n if (cur.equals(endWord) ) break;\n char[] charCur = cur.toCharArray();\n for (int i = 0; i < cur.length(); i++) {\n char c = charCur[i];\n for (char j = \'a\'; j <= \'z\'; j++) {\n charCur[i] = j;\n String s = new String(charCur);\n if (set.contains(s) && dist.get(s) == null) {\n dist.put(s, dist.get(cur) + 1);\n q.offer(s);\n }\n \n }\n charCur[i] = c;\n }\n }\n }\n \n private void dfs(String word, List<String> path) {\n if (word.equals(beginWord)) {\n List list = new ArrayList(path);\n Collections.reverse(list);\n res.add(list);\n return;\n }\n char[] charCur = word.toCharArray();\n for (int i = 0; i < word.length(); i++) {\n char c = charCur[i];\n for (char j = \'a\'; j <= \'z\'; j++) {\n charCur[i] = j;\n String s = new String(charCur);\n if (dist.get(s) != null && dist.get(s) + 1 == dist.get(word)) {\n path.add(s);\n dfs(s, path);\n path.remove(path.size() - 1);\n }\n \n }\n charCur[i] = c;\n }\n }\n}\n```\n**Upvote if you like the solution** | 7 | 1 | ['Depth-First Search', 'Java'] | 2 |
word-ladder-ii | 0 ms Runtime - C++ | 0-ms-runtime-c-by-day_tripper-h1dx | \nclass Solution {\npublic:\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n auto answer = std::ve | Day_Tripper | NORMAL | 2022-08-14T04:34:09.996904+00:00 | 2022-08-14T05:03:57.312276+00:00 | 832 | false | ```\nclass Solution {\npublic:\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n auto answer = std::vector<std::vector<std::string>>();\n auto from = beginWord;\n auto to = endWord;\n\n auto my_lexicon = std::unordered_set<std::string>(wordList.begin(),wordList.end());\n if ((my_lexicon.find(to) == my_lexicon.end())) {\n\t return answer;\n\t }\n //auto const total_lexicon = my_lexicon;\n\n auto current_level_forward = std::unordered_set<std::string>({from});\n auto current_level_backward = std::unordered_set<std::string>({to});\n auto ladders = std::unordered_map<std::string, std::vector<std::string>>();\n\n auto found = false;\n auto flip = false;\n\n my_lexicon.erase(from);\n my_lexicon.erase(to);\n\n while (!current_level_forward.empty() and !current_level_backward.empty()) {\n\n if (current_level_forward.size() > current_level_backward.size()) {\n flip = !flip;\n std::swap(current_level_forward, current_level_backward);\n }\n\n auto next_level = std::unordered_set<std::string>();\n\n for (auto word: current_level_forward) {\n //auto neighbours = find_neighbours(word, total_lexicon);\n for (std::string::size_type i = 0; i < word.size(); i++) {\n auto neighbour = word;\n for (auto j = \'a\'; j <= \'z\'; j++) {\n if (neighbour[i] == j) continue;\n neighbour[i] = j;\n\n if (current_level_backward.find(neighbour) != current_level_backward.end()) {\n found = true;\n flip ? ladders[neighbour].emplace_back(word) : ladders[word].emplace_back(neighbour);\n }\n if (my_lexicon.find(neighbour) != my_lexicon.end()) {\n next_level.insert(neighbour);\n flip ? ladders[neighbour].emplace_back(word) : ladders[word].emplace_back(neighbour);\n }\n }\n }\n }\n if (found) break;\n for (auto seen: next_level) my_lexicon.erase(seen);\n current_level_forward = next_level;\n }\n\n if (found) {\n auto current_path = std::vector<std::string>({from});\n generate_paths(from, to, ladders, answer);\n }\n return answer;\n \n}\nprivate:\n auto generate_paths(std::string from, std::string const& to, std::unordered_map<std::string, std::vector<std::string>>& ladders,\n std::vector<std::vector<std::string>>& answer)\n -> void { \n \n auto paths_to_search = std::vector<std::vector<std::string>>();\n paths_to_search.push_back(std::vector<std::string>({from}));\n \n while(!paths_to_search.empty()) {\n auto current_path = paths_to_search.back();\n paths_to_search.pop_back();\n \n auto current_word = current_path.back();\n \n if (current_word == to) {\n answer.push_back(current_path);\n continue;\n }\n \n if (ladders.find(current_word) == ladders.end()) {\n continue;\n }\n \n for (const auto& word: ladders.at(current_word)) {\n auto path = current_path;\n path.push_back(word);\n paths_to_search.push_back(path);\n } \n }\n }\n};\n```\n\nAlternate Solution using Trie :\n\n```\nclass node{\n public:\n char data;\n map<char, node*> h; // if a in h then it has its address\n node(char d){\n data = d;\n }\n};\n\nclass Trie{\n node* root;\n public:\n Trie(){\n root = new node(\'\\0\'); // initial root which will contain map of first charachter\n }\n\n void insert(string& word){\n node* temp = root;\n for(int i = 0; i < word.size(); i++){\n char ch = word[i];\n if(temp->h.count(ch) == 0){ // if this character not present in previous charachter map\n node* child = new node(ch);\n temp->h[ch] = child;\n }\n temp = temp->h[ch];\n }\n }\n\n bool isPresent(string& word){\n node* temp = root;\n for(int i = 0; i < word.size(); i++){\n char ch = word[i];\n if(temp->h.count(ch)) temp = temp->h[ch];\n else return 0;\n }\n return 1;\n }\n};\nvector<vector<string>> ans;\nvoid bfs(string& a, string& b, map<string, vector<string>>& parent, Trie& s){\n map<string, int> dis;\n dis[a] = 1;\n deque<string> que = {a};\n parent[a] = {a};\n int l = a.size();\n while(!que.empty()){\n string v = que[0];\n int d = dis[v];\n string e = que[0];\n que.pop_front();\n for(int i = 0; i < l; i++){\n char cur = v[i];\n for(int j = 0; j < 26; j++){\n v[i] = j + \'a\';\n if (v[i] == cur) continue;\n if (s.isPresent(v)){\n if (dis.count(v) == 0 || dis[v] > d + 1){\n dis[v] = d + 1;\n parent[v].emplace_back(e);\n que.emplace_back(v);\n }\n else if (dis[v] == d + 1){\n parent[v].emplace_back(e);\n }\n }\n }\n v[i] = cur;\n }\n }\n}\n\nvoid getanswer(string& a, map<string, vector<string>>& parent, deque<string>& store){\n if (parent[a][0] == a){\n vector<string> v(store.begin(), store.end());\n ans.emplace_back(v);\n return;\n }\n for(auto& i : parent[a]){\n store.emplace_front(i);\n getanswer(i, parent, store);\n store.pop_front();\n }\n}\nclass Solution {\npublic:\n vector<vector<string>> findLadders(string start, string end, vector<string>& dict) {\n ans = {};\n Trie s;\n for(auto& i : dict){\n s.insert(i);\n }\n map<string, vector<string>> parent;\n bfs(start, end, parent, s);\n if (parent.count(end) == 0){\n return {};\n }\n deque<string> store = {end};\n getanswer(end, parent, store);\n return ans;\n }\n};\n```\n\nAlternate Solution using DFS + Dictionary :\n\n```\nclass Solution {\npublic:\n /*\n min path of a graph: each vertex is a word in the dictionary list\n \n How to backtrack path in Dijkstra or BFS?\n \n from end, for all adjacent nodes to end, if dist[adj] + 1 = dist[end], adj is a node in the min path.\n \n end. --- a dist[a] + 1 ==? dist[end]\n |-- b\n |-- c\n \n BFS solution, use dist[i] record the min path of each word from src\n */\n unordered_set<string> dict;\n unordered_map<string, int> dist;\n string src, dst;\n \n vector<vector<string>> res;\n vector<string> path;\n \n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n src = beginWord, dst = endWord;\n for (auto& word : wordList) dict.insert(word);\n queue<string> que;\n dist[src] = 0;\n que.push(src);\n while (!que.empty()) {\n auto t = que.front();\n que.pop();\n if (t == dst) break;\n string bk = t;\n for (int i = 0; i < t.size(); i++) {\n t = bk; \n // enumerate all possible adjacent words\n for (int j = \'a\'; j <= \'z\'; j++) {\n t[i] = j;\n // if in dictionary and dist has not been updated\n if (dict.count(t) && dist.count(t) == 0) {\n dist[t] = dist[bk] + 1;\n que.push(t);\n }\n }\n }\n }\n \n // backtrack path\n if (dist.count(dst)) {\n path.push_back(dst);\n dfs(dst);\n }\n \n return res;\n }\n \nprivate:\n \n // cannot use reference here\n void dfs(string u) {\n if (u == src) {\n reverse(path.begin(), path.end());\n res.push_back(path);\n reverse(path.begin(), path.end());\n return;\n }\n \n string bk = u;\n for (int i = 0; i < u.size(); i++) {\n u = bk;\n for (int j = \'a\'; j <= \'z\'; j++) {\n u[i] = j;\n if (dist.count(u) && dist[u] + 1 == dist[bk]) {\n path.push_back(u);\n dfs(u);\n path.pop_back();\n }\n }\n }\n }\n};\n```\n\n\n | 7 | 1 | [] | 0 |
word-ladder-ii | 🗓️ Daily LeetCoding Challenge August, Day 14 | daily-leetcoding-challenge-august-day-14-xt2s | This problem is the Daily LeetCoding Challenge for August, Day 14. Feel free to share anything related to this problem here! You can ask questions, discuss what | leetcode | OFFICIAL | 2022-08-14T00:00:50.120940+00:00 | 2022-08-14T00:00:50.121008+00:00 | 5,464 | false | This problem is the Daily LeetCoding Challenge for August, Day 14.
Feel free to share anything related to this problem here!
You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made!
---
If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide
- **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem.
- **Images** that help explain the algorithm.
- **Language and Code** you used to pass the problem.
- **Time and Space complexity analysis**.
---
**📌 Do you want to learn the problem thoroughly?**
Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/word-ladder-ii/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis.
<details>
<summary> Spoiler Alert! We'll explain these 2 approaches in the official solution</summary>
**Approach 1:** Breadth-First Search (BFS) + Backtracking
**Approach 2:** Bidirectional Breadth-First Search (BFS) + Backtracking
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)!
---
<br>
<p align="center">
<a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank">
<img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" />
</a>
</p>
<br> | 7 | 4 | [] | 41 |
word-ladder-ii | Time Limit Exceeded for "nape", "mild" | time-limit-exceeded-for-nape-mild-by-cen-d2bu | I used BFS approach and kept a map for getting paths. I used dp approach for faster retrievel but i am still getting TLE for "nape" "mild" input (achieved to ge | cengin | NORMAL | 2014-01-30T11:44:14+00:00 | 2014-01-30T11:44:14+00:00 | 5,517 | false | I used BFS approach and kept a map for getting paths. I used dp approach for faster retrievel but i am still getting TLE for "nape" "mild" input (achieved to get correct results on my pc). Can anyone point ways to decrease time consumption?\n\n\n public ArrayList<ArrayList<String>> findLadders(String start,\n \t\t\tString end, HashSet<String> dict) {\n \n \t\tArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();\n \t\tQueue<String> que = new LinkedList<String>();\n \t\tque.add(start);\n \t\tString dummy = "dummuuuOO";\n \t\tHashSet<String> used = new HashSet<String>();\n \t\tif (!dict.contains(end))\n \t\t\treturn ret;\n \t\tque.add(dummy);\n \t\tdict.remove(start);\n \t\tHashMap<String, Set<String>> path = new HashMap<String, Set<String>>();\n \t\tHashSet<String> usedTemp = new HashSet<String>();\n \t\tHashMap<String, ArrayList<String>> dictMemory = new HashMap<String, ArrayList<String>>();\n \t\tint count = 0;\n \t\twhile (que.size() > 1) {\n \t\t\tString current = que.poll();\n \t\t\tif (current.equals(end)) {\n \t\t\t\tHashMap<String, ArrayList<ArrayList<String>>> mem = new HashMap<String, ArrayList<ArrayList<String>>>();\n \t\t\t\tret.addAll(generateList(start, end, path, mem, count));\n \t\t\t\tbreak;\n \t\t\t}\n \t\t\tif (current.equals(dummy)) {\n \t\t\t\tcount++;\n \t\t\t\tque.add(dummy);\n \t\t\t\tused.addAll(usedTemp);\n \t\t\t\tusedTemp.clear();\n \t\t\t\tcontinue;\n \t\t\t}\n \t\t\tArrayList<String> list = getNextFromDict(current, dict, dictMemory, end);\n \t\t\tfor (String next : list) {\n \t\t\t\tif (!used.contains(next)) {\n \t\t\t\t\tSet<String> nl = path.get(next) == null ? new HashSet<String>()\n \t\t\t\t\t\t\t: path.get(next);\n \t\t\t\t\tnl.add(current);\n \t\t\t\t\tpath.put(next, nl);\n \t\t\t\t\tusedTemp.add(next);\n \t\t\t\t\tque.add(next);\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t\treturn ret;\n \t}\n \n \tprivate ArrayList<String> getNextFromDict(String current,\n \t\t\tHashSet<String> dict, HashMap<String, ArrayList<String>> dictMemory, String last) {\n \t\tif (dictMemory.get(current) != null)\n \t\t\treturn dictMemory.get(current);\n \t\tArrayList<String> ret = new ArrayList<String>();\n \t\tfor (int n = 0; n < current.length(); n++) {\n \t\t\tString check = current.substring(0, n) + String.valueOf(last.charAt(n))\n \t\t\t\t\t+ current.substring(n + 1);\n \t\t\tif (dict.contains(check))\n \t\t\t\tret.add(check);\n \t\t\tfor (char c = 'a'; c < 'z'; c++) {\n \t\t\t\tif (current.charAt(n) != c && last.charAt(n) != c) {\n \t\t\t\t\tString key = current.substring(0, n) + String.valueOf(c)\n \t\t\t\t\t\t\t+ current.substring(n + 1);\n \t\t\t\t\tif (dict.contains(key))\n \t\t\t\t\t\tret.add(key);\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t\tdictMemory.put(current, ret);\n \t\treturn ret;\n \t}\n \n \tprivate ArrayList<ArrayList<String>> generateList(String start,\n \t\t\tString end, HashMap<String, Set<String>> path,\n \t\t\tHashMap<String, ArrayList<ArrayList<String>>> memory, int count) {\n \t\tArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();\n \t\tif (count < 0)\n \t\t\treturn null;\n \t\tif (memory.get(end) != null) {\n \t\t\tif (memory.get(end) != null && memory.get(end).size() > 0\n \t\t\t\t\t&& memory.get(end).get(0).size() == count+1){\n \t\t\t\tArrayList<ArrayList<String>> cache1 = new ArrayList<ArrayList<String>>();\n \t\t\t\tArrayList<String> cache2 = new ArrayList<String>();\n \t\t\t\tcache2.addAll(memory.get(end).get(0));\n \t\t\t\tcache1.add(cache2);\n \t\t\t\treturn cache1;\n \t\t\t}\n \t\t\telse\n \t\t\t\treturn null;\n \t\t}\n \t\tString key = end;\n \t\tif (key.equals(start)) {\n \t\t\tArrayList<String> l = new ArrayList<String>();\n \t\t\tl.add(key);\n \t\t\tret.add(l);\n \t\t\tArrayList<ArrayList<String>> retClone = new ArrayList<ArrayList<String>>();\n \t\t\tfor (ArrayList<String> list : ret) {\n \t\t\t\tArrayList<String> lClone = new ArrayList<String>();\n \t\t\t\tlClone.addAll(list);\n \t\t\t\tretClone.add(lClone);\n \t\t\t}\n \t\t\tmemory.put(end, retClone);\n \t\t\treturn ret;\n \t\t}\n \n \t\tSet<String> prev = path.get(key);\n \t\tfor (String p : prev) {\n \t\t\tArrayList<ArrayList<String>> generateList = generateList(start, p,\n \t\t\t\t\tpath, memory, count-1);\n \t\t\tif (generateList != null) {\n \t\t\t\tfor (ArrayList<String> pth : generateList) {\n \t\t\t\t\tpth.add(key);\n \t\t\t\t\tret.add(pth);\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t\tArrayList<ArrayList<String>> retClone = new ArrayList<ArrayList<String>>();\n \t\tfor (ArrayList<String> list : ret) {\n \t\t\tArrayList<String> lClone = new ArrayList<String>();\n \t\t\tlClone.addAll(list);\n \t\t\tretClone.add(lClone);\n \t\t}\n \t\tmemory.put(end, retClone);\n \t\treturn ret;\n \t} | 7 | 0 | [] | 9 |
word-ladder-ii | c++ solution using dfs || NO TLE!! | c-solution-using-dfs-no-tle-by-yash_jain-czsa | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | yash_jain26 | NORMAL | 2023-10-16T20:25:56.876724+00:00 | 2023-10-16T20:25:56.876742+00:00 | 812 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n unordered_map<string,int> mp;\n vector<vector<string>> ans;\n string b;\n\n void dfs(string word,vector<string> &seq){\n if(word == b){\n reverse(seq.begin(),seq.end());\n ans.push_back(seq);\n reverse(seq.begin(),seq.end());\n return;\n }\n\n int n = word.size();\n int steps = mp[word];\n\n for(int i = 0; i < n; i++){\n char org = word[i];\n for(char c = \'a\'; c <= \'z\';c++){\n word[i] = c;\n if(mp.find(word) != mp.end() && mp[word] + 1 == steps){\n seq.push_back(word);\n dfs(word,seq);\n seq.pop_back();\n }\n }\n word[i] = org;\n }\n }\n\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n unordered_set<string> st(wordList.begin(),wordList.end());\n queue<string> q;\n q.push(beginWord);\n\n st.erase(beginWord);\n mp[beginWord] = 1;\n int n = beginWord.size();\n b = beginWord; \n\n while(!q.empty()){\n string word = q.front();\n int steps = mp[word];\n q.pop();\n\n if(word == endWord) break;\n\n for(int i = 0; i < n; i++){\n char org = word[i];\n for(char c = \'a\'; c <= \'z\';c++){\n word[i] = c;\n if(st.count(word) > 0){\n st.erase(word);\n q.push(word);\n mp[word] = steps + 1;\n }\n }\n word[i] = org;\n }\n }\n\n if(mp.find(endWord) != mp.end()){\n vector<string> seq;\n seq.push_back(endWord);\n dfs(endWord,seq);\n }\n return ans;\n }\n};\n``` | 6 | 0 | ['String', 'Backtracking', 'Depth-First Search', 'Graph', 'C++'] | 0 |
word-ladder-ii | Word Ladder II || BFS + Backtracking with explanation | word-ladder-ii-bfs-backtracking-with-exp-45ob | BFS + Backtracking\n\nHere we have given that Every adjacent pair of words differs by a single letter. In order to find such pairs efficiently, we can replace e | meetpatel5720 | NORMAL | 2022-08-14T09:43:51.331667+00:00 | 2022-08-14T09:43:51.331713+00:00 | 917 | false | ### BFS + Backtracking\n\nHere we have given that Every adjacent pair of words differs by a single letter. In order to find such pairs efficiently, we can **replace** each character of `word` with `*` and create a hash map where key will be new pattern and value will be list of words.\n\nFor example `word1 = hit` and `word2 = hot` and hash map will look like this.\n\n\n\nWe can use this as an **adjacency list** to go from one node to other nodes.\n\nNow, our task is to find **shortest transformation sequences**. This is hint for **BFS**. So first we will do BFS from `beginWord` to `endWord`. This will give us directed graph where parent node will be word and all it\'s children will be adjacent words differs by a single letter from parent word.\n\nWhile doing BFS we will also keep track of word and at which level that word appears. This will help us later while generating sequences from graph using backtracking.\n\nOnce we have graph, we use **backtracking** do generate all sequences starting from `beginWord`.\n\n***After leetcode updated the test cases for this problem, backtracking from `beginWord` is giving TLE. So we will start backtracing from `endWord` and we work towards `beginWord`.***\n\n**Example**\n\n\n\nLooking at this image you might think that this graph has links from top to bottom only, but if you debug the code then you will see it stores link to parent node as well. This will allow us to do backtracking from `endWord`. \n\n**Algorithm**\n- Create adjacency list\n- Build graph from `beginWord` to `endWord` using BFS.\n- Generate sequences using **backtracking**\n\n```java\nclass Solution {\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n Set<String> words = new HashSet<>(wordList);\n if (!words.contains(endWord)) {\n return new ArrayList<>();\n }\n\n words.add(beginWord);\n\n HashMap<String, List<String>> adjList = new HashMap<>();\n\n for (String word: words) {\n for (int i = 0; i < word.length(); i++) {\n String pattern = getPattern(word, i);\n adjList.putIfAbsent(pattern, new ArrayList<>());\n adjList.get(pattern).add(word);\n }\n }\n\n Queue<String> queue = new LinkedList<>();\n HashMap<String, Set<String>> graph = new HashMap<>();\n Map<String, Integer> levels = new HashMap<>();\n\n queue.add(beginWord);\n levels.put(beginWord, 0);\n\n while (!queue.isEmpty()) {\n String cur = queue.poll();\n int curLevel = levels.get(cur);\n graph.putIfAbsent(cur, new HashSet<>());\n\n for (int i = 0; i < cur.length(); i++) {\n String pattern = getPattern(cur, i);\n\n for (String nei: adjList.get(pattern)) {\n \n graph.get(cur).add(nei);\n if (!levels.containsKey(nei)) {\n levels.put(nei, curLevel + 1);\n queue.add(nei);\n }\n }\n }\n }\n \n List<List<String>> ans = new ArrayList<>();\n if (!graph.containsKey(endWord)) {\n return ans; \n }\n\n backtracking(endWord, beginWord, new ArrayList<>(), ans, graph, levels);\n\n return ans;\n }\n\n private void backtracking(String start, String endWord,\n List<String> path, List<List<String>> ans,\n HashMap<String, Set<String>> graph,\n Map<String, Integer> levels) {\n path.add(start);\n\n if (start.equals(endWord)) {\n List<String> temp = new ArrayList<>(path);\n Collections.reverse(temp);\n ans.add(temp);\n } else {\n for (String next : graph.get(start)) {\n if (levels.get(next) == levels.get(start) - 1) {\n backtracking(next, endWord, path, ans, graph, levels);\n }\n }\n }\n\n path.remove(path.size() - 1);\n }\n\n private String getPattern(String word, int i) {\n return word.substring(0, i) + "*" + word.substring(i + 1);\n }\n}\n```\n\n**Help** - I was not able to come up with correct time & space complexity for this solution. Please add it in comment if anyone has answer to this. Many thanks!! | 6 | 0 | ['Backtracking', 'Breadth-First Search', 'Java'] | 1 |
word-ladder-ii | Why is this question | why-is-this-question-by-mayur_madhwani-86ac | All you get is TLE\nWhen you try to understand someone else\'s code and finally try to implement it you get TLE\nI don\'t know what\'s wrong with this question\ | mayur_madhwani | NORMAL | 2022-08-14T05:37:14.756555+00:00 | 2022-08-14T14:00:03.676061+00:00 | 724 | false | All you get is TLE\nWhen you try to understand someone else\'s code and finally try to implement it you get TLE\nI don\'t know what\'s wrong with this question\nWhat do I need to do to get this question done | 6 | 0 | [] | 5 |
word-ladder-ii | C# Solution | BFS, DFS, Backtracking, Dictionary, Clean code | c-solution-bfs-dfs-backtracking-dictiona-jy35 | C#\npublic class Solution {\n public IList<IList<string>> FindLadders(string beginWord, string endWord, IList<string> wordList) {\n List<IList<string> | tonytroeff | NORMAL | 2022-08-14T05:07:06.325532+00:00 | 2022-08-14T05:07:06.325577+00:00 | 333 | false | ```C#\npublic class Solution {\n public IList<IList<string>> FindLadders(string beginWord, string endWord, IList<string> wordList) {\n List<IList<string>> ans = new List<IList<string>>();\n var (shortestPathLength, graph) = ComputeGraph(beginWord, endWord, wordList);\n if (graph == null) return ans;\n \n string[] path = new string[shortestPathLength];\n FindPaths(endWord, 0);\n return ans;\n \n void FindPaths(string w, int position) {\n path[shortestPathLength - (position + 1)] = w;\n if (position == shortestPathLength - 1) ans.Add(path.ToList());\n else if (graph.ContainsKey(w))\n foreach (string nextWord in graph[w]) FindPaths(nextWord, position + 1);\n }\n }\n \n private static (int ShortestPathLength, Dictionary<string, HashSet<string>> Graph) ComputeGraph(string beginWord, string endWord, IList<string> wordList) {\n Dictionary<string, HashSet<string>> graph = new Dictionary<string, HashSet<string>>();\n \n Queue<string> q = new Queue<string>();\n q.Enqueue(beginWord);\n \n HashSet<string> used = new HashSet<string>(capacity: wordList.Count + 1);\n HashSet<string> usedInIteration = new HashSet<string>(capacity: wordList.Count + 1);\n bool endIsReached = false;\n int pathLength = 1;\n while (q.Count > 0) {\n int iterationCount = q.Count;\n \n for (int i = 0; i < iterationCount; i++) {\n string current = q.Dequeue();\n used.Add(current);\n \n foreach (string possibleContinuation in wordList.Where(w => !used.Contains(w) && HaveOneLetterDifference(w, current))) {\n if (possibleContinuation == endWord) endIsReached = true;\n else if (!usedInIteration.Contains(possibleContinuation)) {\n q.Enqueue(possibleContinuation);\n usedInIteration.Add(possibleContinuation);\n }\n \n if (!graph.ContainsKey(possibleContinuation)) graph[possibleContinuation] = new HashSet<string>();\n graph[possibleContinuation].Add(current);\n }\n }\n \n if (endIsReached) return (pathLength + 1, graph);\n\n foreach (string usedContinuation in usedInIteration) used.Add(usedContinuation);\n usedInIteration.Clear();\n pathLength++;\n }\n \n return (int.MaxValue, null);\n }\n \n private static bool HaveOneLetterDifference(string a, string b) {\n bool hadDifference = false;\n for (int i = 0; i < a.Length; i++) {\n if (a[i] != b[i]) {\n if (hadDifference) return false;\n else hadDifference = true;\n }\n }\n \n return hadDifference;\n }\n}\n``` | 6 | 0 | ['Depth-First Search', 'Breadth-First Search'] | 2 |
word-ladder-ii | ✅python: fast optimized bfs + adjacency list + parent list, easy to understand with comments | python-fast-optimized-bfs-adjacency-list-1xtl | ```\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n #generate adjacent list\n | zoey513 | NORMAL | 2022-08-04T18:14:43.997881+00:00 | 2022-08-04T18:17:26.250443+00:00 | 393 | false | ```\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n #generate adjacent list\n Nei = defaultdict(list)\n for word in wordList:\n for i in range(len(word)):\n pattern = word[:i]+\'*\'+word[i+1:]\n Nei[pattern].append(word) \n \n #breadth first search + generate parent dictionary with path length limit\n seen = {beginWord:0}\n q = deque([(beginWord,0)])\n minDist = float("inf")\n Parent = defaultdict(set)\n while q: \n for _ in range(len(q)):\n pre,dis = q.popleft()\n for i in range(len(pre)):\n pattern = pre[:i] + "*" + pre[i+1:]\n for neighbor in Nei[pattern]:\n if neighbor not in seen or (seen[neighbor] == dis + 1 and seen[neighbor] <= minDist):\n if neighbor == endWord: \n minDist = dis + 1\n Parent[neighbor].add(pre)\n if neighbor not in seen: \n q.append((neighbor,dis+1))\n seen[neighbor] = dis + 1\n\t\t\t\t\t\t\t\t\n #generate path from parent dictionary\n def makeList(cur,Path):\n if cur == beginWord:\n res.append(Path)\n else:\n for parent in Parent[cur]:\n makeList(parent,[parent] + Path)\n res = []\n makeList(endWord,[endWord])\n \n #return results\n return res\n \n \n | 6 | 0 | [] | 0 |
word-ladder-ii | Python BFS+DFS beats100% | python-bfsdfs-beats100-by-juehuil-vtkb | python\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n prefix_d = defaultdict(list)\ | juehuil | NORMAL | 2022-03-28T02:32:02.704173+00:00 | 2022-03-28T02:33:11.318221+00:00 | 776 | false | ```python\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n prefix_d = defaultdict(list)\n for word in wordList:\n for i in range(0,len(word)):\n prefix_d[word[0:i]+"*"+word[i+1:]].append(word)\n \n order = {beginWord: []}\n queue = deque([beginWord])\n temp_q = deque()\n go_on = True\n end_list = []\n \n while queue and go_on: # There is no node even added to temp_q\n temp_d = {}\n while queue: # Pop every node on this level\n cur = queue.popleft()\n for i in range(0, len(cur)):\n for j in prefix_d[cur[0:i]+"*"+cur[i+1:]]:\n if j == endWord:\n end_list.append(j)\n go_on = False\n if j not in order:\n if j not in temp_d:\n temp_d[j] = [cur]\n temp_q.append(j)\n else:\n temp_d[j].append(cur)\n queue = temp_q\n temp_q = deque()\n order.update(temp_d)\n \n ret = []\n \n # DFS to restore the paths\n def dfs(path, node):\n path = path + [node] # add the node(Deepcopy)\n if order[node] == []:\n ret.append(list(path[::-1]))\n return\n for i in order[node]:\n dfs(path, i)\n if endWord in order:\n dfs([], endWord)\n else:\n return []\n \n return ret\n```\n | 6 | 0 | ['Python', 'Python3'] | 2 |
word-ladder-ii | My javascript solution | my-javascript-solution-by-tyz111-inyu | This is a solution using both BFS and DFS.\n step1: BFS is used to calcuted the shortest length from beginWord to endWord. (function findShortestLen)\n step2: I | tyz111 | NORMAL | 2021-02-23T05:25:45.197807+00:00 | 2021-02-28T04:17:30.950066+00:00 | 819 | false | This is a solution using both BFS and DFS.\n* step1: BFS is used to calcuted the shortest length from beginWord to endWord. (function findShortestLen)\n* step2: In the meantime of step1, twp maps are built, that is Map wordToShortest(key: word, value: the shortest distance from this word to endWord) and Map wordToNeighbors(key: word, value: all its neighbors in wordList). \n * Note: To make wordToShortest in which the value is the distance to endWord, we should start BFS from endWord. Map wordToShortest is useful in step3.\n* step3: DFS is used to find all ladders from beginWord to endWord. A trick to reduce the executing time is to start DFS from beginWord(different from BFS) and **only add word that is one step nearer to the endWord** than the last word just added to current ladder.(The two maps we build in step2 are used here.) \n * In this way, we do not need to add all beginWord\'s neighbors, and then all neighbors of neighbors, etc. So we can reduce the times of recursion at a large scale.\n```javascript\n/**\n * @param {string} beginWord\n * @param {string} endWord\n * @param {string[]} wordList\n * @return {string[][]}\n */\n\nvar findLadders = function(beginWord, endWord, wordList) {\n if (!wordList.includes(endWord)) return []\n if (beginWord === endWord) return [[beginWord]]\n wordList.push(beginWord)\n const wordToNeighbors = new Map()\n const wordToShortest = new Map()\n const shortestLen = findShortestLen(beginWord, endWord)\n const ladders = []\n const curLadder = [beginWord]\n recursion(beginWord, shortestLen)\n return ladders\n\n \n function recursion(curWord, curShortest) {\n if (curShortest === 0) {\n ladders.push([...curLadder])\n return\n }\n const neighbors = findAllNeighbors(curWord)\n for (let neighbor of neighbors) {\n if (!wordToShortest.has(neighbor) || wordToShortest.get(neighbor) != curShortest - 1) continue\n curLadder.push(neighbor)\n recursion(neighbor, curShortest - 1)\n curLadder.pop()\n }\n }\n \n \n function findShortestLen(beginWord, endWord) {\n const queue = []\n queue.push(endWord)\n let count = 0\n wordToShortest.set(endWord, count)\n while (queue.length !== 0) {\n count++;\n const size = queue.length\n for (let i = 0; i < size; i++) {\n const curLast = queue.shift()\n const neighbors = findAllNeighbors(curLast)\n for (let neighbor of neighbors) {\n if (wordToShortest.has(neighbor)) continue\n wordToShortest.set(neighbor, count)\n if (neighbor === beginWord) {\n return count\n }\n queue.push(neighbor)\n }\n }\n }\n return -1\n }\n \n function findAllNeighbors(word) {\n if (wordToNeighbors.has(word)) return wordToNeighbors.get(word)\n neighbors = []\n for (let w of wordList) {\n if (isNeighbor(word, w)) {\n neighbors.push(w)\n }\n }\n wordToNeighbors.set(word, neighbors)\n return neighbors\n }\n \n function isNeighbor(w1, w2) {\n if (w1.length !== w2.length) return false\n let diff = 0\n for (let i = 0; i < w1.length; i++) {\n if (w1.charAt(i) !== w2.charAt(i)) {\n diff++\n if (diff > 1) return false\n }\n }\n return diff === 1\n }\n};\n``` | 6 | 0 | ['JavaScript'] | 5 |
word-ladder-ii | C++ BFS+DFS ,58% faster, well commented | c-bfsdfs-58-faster-well-commented-by-shy-xow4 | \nclass Solution {\npublic:\n\n vector<vector<string>> ans; //store all ans\n \n void DFS(string& beginWord,string& endWord,unordered_map<string, unord | Shyamji07 | NORMAL | 2021-01-10T08:22:16.813985+00:00 | 2022-07-23T20:57:40.838838+00:00 | 293 | false | ```\nclass Solution {\npublic:\n\n vector<vector<string>> ans; //store all ans\n \n void DFS(string& beginWord,string& endWord,unordered_map<string, unordered_set<string>>& adj,vector<string>&path){\n path.push_back(beginWord);\n if(beginWord==endWord){\n ans.push_back(path);\n path.pop_back();\n return;\n }\n for(auto x: adj[beginWord])\n DFS(x,endWord,adj,path);\n path.pop_back(); //backtracking\n }\n \n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n ios_base::sync_with_stdio(0);\n cin.tie(NULL);\n unordered_map<string, unordered_set<string>>adj;\n unordered_set<string>dict(wordList.begin(),wordList.end());\n \n queue<string> q;//for bfs traversal\n q.push(beginWord); //push start node\n unordered_map<string,int>visited; //key->string whivh is node....Value->level{depth of traversal}\n visited[beginWord]=0;//start node at level 0\n while(!q.empty())\n {\n string curr=q.front();\n q.pop();\n string temp=curr;\n for(int i=0;i<curr.size();i++)\n {\n for(char x=\'a\';x<=\'z\';x++)\n {\n if(temp[i]==x)//skip if same letter\n continue;\n temp[i]=x;\n if(dict.count(temp)>0)//check if new word is present in wordList\n {\n if(visited.count(temp)==0)//check if the new word was already visited\n {\n visited[temp]=visited[curr]+1;\n q.push(temp);\n adj[curr].insert(temp);\n }\n else if(visited[temp]==visited[curr]+1)//if already visited and new word is child\n adj[curr].insert(temp);\n }\n }\n temp[i]=curr[i]; //revert back temp to curr\n }\n }\n // dfs: find all possible path at min depth\n vector<string>path;\n DFS(beginWord,endWord,adj,path);\n return ans;\n }\n};\n```\n**upvote if u like soln** | 6 | 0 | [] | 1 |
word-ladder-ii | JAVA BFS one pass | java-bfs-one-pass-by-mtgk-rw8j | \nclass Solution {\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n List<List<String>> res = new A | mtgk | NORMAL | 2020-05-26T00:05:31.408186+00:00 | 2020-05-26T00:05:31.408235+00:00 | 695 | false | ```\nclass Solution {\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n List<List<String>> res = new ArrayList<>();\n\n if (!wordList.contains(endWord)) return res;\n \n // build graph\n Map<String, List<String>> map = new HashMap<>();\n for (int i = 0; i < wordList.size(); i++) {\n if (!wordList.contains(beginWord) && canTransform(wordList.get(i), beginWord)) {\n buildGraph(map, wordList.get(i), beginWord);\n buildGraph(map, beginWord, wordList.get(i));\n }\n\n for (int j = i + 1; j < wordList.size(); j++) {\n if (canTransform(wordList.get(i), wordList.get(j))) {\n buildGraph(map, wordList.get(i), wordList.get(j));\n buildGraph(map, wordList.get(j), wordList.get(i));\n }\n }\n }\n \n // BFS from beginWord to endWord\n Queue<List<String>> queue = new LinkedList<>();\n Set<String> visited = new HashSet<>(); // avoid circle in graph, first pick first reached word\n queue.offer(Arrays.asList(new String[]{beginWord})); // start from beginWord\n\n boolean found = false;\n while (!queue.isEmpty() && !found) { // still have word to search\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n List<String> curList = queue.poll();\n String curWord = curList.get(curList.size() - 1); // last visited word in the result list\n visited.add(curWord);\n \n if (curWord.equals(endWord)) {// shortest path found\n res.add(curList);\n found = true; // stop at this level\n continue;\n }\n \n if(!map.containsKey(curWord)) continue;\n \n for (String child : map.get(curWord)) {\n if (visited.contains(child)) continue;\n List<String> nextList = new ArrayList<>(curList);\n nextList.add(child);\n queue.offer(nextList);\n }\n }\n }\n return res;\n }\n \n \n private boolean canTransform(String word1, String word2) {\n if (word1.length() != word2.length()) return false;\n\n int diff = 0;\n for (int i = 0; i < word1.length(); i++) {\n if (word1.charAt(i) != word2.charAt(i)) diff++;\n if (diff > 1) return false;\n }\n \n return diff == 1;\n }\n \n private void buildGraph(Map<String, List<String>> map, String word1, String word2) {\n List<String> list = map.getOrDefault(word1, new ArrayList<>());\n list.add(word2);\n map.put(word1, list);\n }\n}\n``` | 6 | 0 | [] | 1 |
word-ladder-ii | Python BFS | python-bfs-by-infinute-us7o | If you don\'t know the trick to search for the next word, check out the solution for Word Ladder I.\n\nfrom collections import defaultdict\nclass Solution:\n | infinute | NORMAL | 2019-03-13T00:03:00.348692+00:00 | 2019-03-13T00:03:00.348740+00:00 | 1,038 | false | If you don\'t know the trick to search for the next word, check out the solution for [Word Ladder I](https://leetcode.com/problems/word-ladder/solution/).\n```\nfrom collections import defaultdict\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n graph = defaultdict(set)\n for word in wordList + [beginWord]:\n for i in range(len(word)):\n graph[word[:i] + \'_\' + word[i + 1:]].add(word)\n wordList = set(wordList)\n \n queue = [[beginWord]]\n flag = False\n while queue:\n new_queue = []\n to_remove = set()\n for path in queue:\n for i in range(len(path[-1])):\n for new_word in graph[path[-1][:i] + \'_\' + path[-1][i + 1:]] & wordList:\n new_queue.append(path + [new_word])\n to_remove.add(new_word)\n if new_word == endWord: flag = True\n if flag: return [p for p in new_queue if p[-1] == endWord]\n queue = new_queue[:]\n wordList -= to_remove\n return []\n``` | 6 | 0 | [] | 4 |
word-ladder-ii | Java code based on Dijkstra's algorithm. Accepted. | java-code-based-on-dijkstras-algorithm-a-dqpz | The difference from the Word Ladder solution is that now we need to remember all possible previous nodes in the path to the node when solution is optimal. And a | pavel-shlyk | NORMAL | 2015-01-05T21:28:45+00:00 | 2015-01-05T21:28:45+00:00 | 3,621 | false | The difference from the Word Ladder solution is that now we need to remember all possible previous nodes in the path to the node when solution is optimal. And after that construct all possible path variants.\n\n static private class WordVertex implements Comparable<WordVertex>{\n\t\t\n\t\tprivate String word;\n\t\tprivate int dist;\n\t\tprivate List<WordVertex> prev;\n\t\tprivate HashSet<WordVertex> neighbors;\n\t\t\n\t\tprivate WordVertex(String w) {\n\t\t\tword = w;\n\t\t\tdist = Integer.MAX_VALUE;\n\t\t\tneighbors = new HashSet<WordVertex>();\n\t\t\tprev = new LinkedList<WordVertex>();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int compareTo(WordVertex o) {\n\t\t\tif (dist < o.dist) {\n\t\t\t\treturn -1;\n\t\t\t} else if (dist > o.dist) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tpublic List<List<String>> findLadders(String start, String end, Set<String> dict) {\n\t\t\n\t\t// Init vertices\n\t\tWordVertex startVertex = new WordVertex(start);\n\t\tWordVertex endVertex = new WordVertex(end);\n\t\tstartVertex.dist = 0;\n\t\tList<WordVertex> vertices = new ArrayList<WordVertex>();\n\t\tvertices.add(startVertex);\n\t\tvertices.add(endVertex);\n\t\tfor (String word:dict) {\n\t\t\tvertices.add(new WordVertex(word));\n\t\t}\n\t\t\n\t\t// Construct graph\n\t\tfor(int i=0; i<vertices.size(); i++) {\n\t\t\tWordVertex vertex = vertices.get(i);\n\t\t\tfor(int j=i+1; j<vertices.size(); j++) {\n\t\t\t\tWordVertex neighbor = vertices.get(j);\n\t\t\t\tint diff = 0;\n\t\t\t\tfor (int k=0; k<vertex.word.length(); k++) {\n\t\t\t\t\tif (vertex.word.charAt(k) != neighbor.word.charAt(k) && diff++ == 1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (diff == 1) {\n\t\t\t\t\tvertex.neighbors.add(neighbor);\n\t\t\t\t\tneighbor.neighbors.add(vertex);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Find shortest path. Dijkstra's algorithm.\n\t\tPriorityQueue<WordVertex> queue = new PriorityQueue<WordVertex>();\n\t\tfor (WordVertex v:vertices) {\n\t\t\tqueue.add(v);\n\t\t}\n\t\twhile(!queue.isEmpty()) {\n\t\t\tWordVertex v = queue.poll();\n\t\t\tif (v.dist == Integer.MAX_VALUE) continue;\n\t\t\tfor (WordVertex n:v.neighbors) {\n\t\t\t\tif (v.dist + 1 <= n.dist) {\n\t\t\t\t\tn.dist = v.dist + 1;\n\t\t\t\t\tn.prev.add(v); // as one of the previous candidates\n\t\t\t\t\tqueue.remove(n);\n\t\t\t\t\tqueue.add(n);\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t\t\n\t\t// Make result\n\t\tList<List<String>> seqs = new LinkedList<List<String>>();\n\t\tLinkedList<String> seq = new LinkedList<String>();\n\t\tconstructSequences(endVertex, startVertex, seq, seqs);\n\t\t\n\t\treturn seqs;\n }\n\t\n\tvoid constructSequences(WordVertex v, WordVertex start, LinkedList<String> seq, List<List<String>> seqs) {\n\t\tseq.addFirst(v.word);\n\t\tif (v == start) {\n\t\t\tseqs.add(new LinkedList<String>(seq));\n\t\t}\n\t\tfor(WordVertex p:v.prev) {\n\t\t\tconstructSequences(p, start, seq, seqs);\n\t\t}\n\t\tseq.removeFirst();\n\t} | 6 | 0 | [] | 2 |
word-ladder-ii | Java solution, beats 98%, with intuition | java-solution-beats-98-with-intuition-by-85ab | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. use BFS to build a g | y_hao1 | NORMAL | 2024-09-06T02:16:32.678116+00:00 | 2024-09-06T02:16:32.678144+00:00 | 286 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. use BFS to build a graph, where the distance from beginWord to all nodes are the shortest (NOT ALL edges are included, and that\'s the key)\n2. then use DFS to get all paths that leads to endWord\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n private int L;\n private boolean hasPath;\n\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList){\n this.L = beginWord.length();\n Set<String> wordSet = new HashSet<>();\n wordSet.addAll(wordList);\n if(!wordSet.contains(endWord)) return new ArrayList<>();\n\n // BFS\n // build a directed graph G with beginWord being the root\n // we guarantee in G, for all nodes, the dis from beginWord is the shortest\n Map<String, List<String>> adjList = new HashMap<String, List<String>>();\n wordSet.remove(beginWord); // beginWord in wordList is useless\n buildAdjList(beginWord, endWord, wordSet, adjList);\n if(this.hasPath==false) return new ArrayList<>();\n\n // DFS\n // get all paths from beginWord to endWord, knowing that all paths have the same shortest length\n // implement a cache to save branches that have already been visited\n return backtrack(adjList, beginWord, endWord, new HashMap<>());\n }\n\n public List<List<String>> backtrack(\n Map<String, List<String>> adjList, \n String currWord, \n String endWord,\n Map<String, List<List<String>>> cache\n ){\n if(cache.containsKey(currWord)) return cache.get(currWord);\n List<List<String>> result = new ArrayList<>();\n if(currWord.equals(endWord)){\n result.add(new ArrayList<>(Arrays.asList(currWord)));\n }else{\n List<String> neighbors = adjList.getOrDefault(currWord, new ArrayList<>());\n for(String neighbor: neighbors){\n List<List<String>> paths = backtrack(adjList, neighbor, endWord, cache);\n for(List<String> path: paths){\n List<String> copy = new ArrayList<>(path);\n copy.add(0, currWord);\n result.add(copy);\n }\n }\n }\n cache.put(currWord, result);\n return result;\n }\n\n public void buildAdjList(String beginWord, String endWord, Set<String> unvisitedWords, Map<String, List<String>> adjList){\n Queue<String> q = new LinkedList<>();\n q.add(beginWord);\n\n while(!q.isEmpty()){\n if(this.hasPath) break;\n int size = q.size();\n Set<String> nextLevelWords = new HashSet<>();\n for(int i=0; i<size; i++){\n String currWord = q.poll();\n List<String> nextLevelNeighbors= getNextLevelNeighbors(currWord, unvisitedWords, adjList);\n // System.out.println(currWord+" neighbors: " + nextLevelNeighbors);\n for(String nextLevelNeighbor: nextLevelNeighbors){\n if(!nextLevelWords.contains(nextLevelNeighbor)){\n if(nextLevelNeighbor.equals(endWord)) this.hasPath = true;\n nextLevelWords.add(nextLevelNeighbor);\n q.add(nextLevelNeighbor);\n }\n }\n }\n // only after adding all edges to next level\n // can we remove next level nodes\n for(String w: nextLevelWords){\n unvisitedWords.remove(w);\n }\n }\n }\n\n public List<String> getNextLevelNeighbors(String word, Set<String> unvisitedWords, Map<String, List<String>> adjList){\n // for every char -- K *\n // replace it with 26 letters -- 26 *\n // check if it exists in wordSet -- O(1)\n List<String> neighbors = new ArrayList<>();\n char[] wordSeq = word.toCharArray();\n for(int i=0; i<this.L; i++){\n char oldC = wordSeq[i];\n for(int j=0; j<26; j++){\n char newC = (char)(\'a\'+j);\n if(newC==oldC) continue;\n wordSeq[i]=newC;\n String newWord = new String(wordSeq);\n if(unvisitedWords.contains(newWord)){\n neighbors.add(newWord);\n }\n wordSeq[i] = oldC;\n }\n }\n adjList.put(word, neighbors);\n return neighbors;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
word-ladder-ii | JAVA FASTEST SOLUTION😉✌️ | java-fastest-solution-by-abhiyadav05-p2lp | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | abhiyadav05 | NORMAL | 2023-08-16T17:06:55.908628+00:00 | 2023-08-16T17:06:55.908654+00:00 | 444 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\nclass Solution {\n String b;\n\n // Create a hashmap of type word->level to get the idea \n // on which level the word comes after the transformations.\n\n HashMap < String, Integer > mpp;\n\n // A list for storing the final answer.\n List < List < String >> ans;\n private void dfs(String word, List < String > seq) {\n\n // Function for implementing backtracking using the created map\n // in reverse order to find the transformation sequence in less time.\n\n // Base condition :\n // If word equals beginWord, we\u2019ve found one of the sequences\n // simply reverse the sequence and return. \n if (word.equals(b)) {\n\n // Since java works with reference, create\n // a duplicate and store the reverse of it\n List < String > dup = new ArrayList < > (seq);\n Collections.reverse(dup);\n ans.add(dup);\n return;\n }\n int steps = mpp.get(word);\n int sz = word.length();\n\n // Replace each character of the word with letters from a-z \n // and check whether the transformed word is present in the map\n // and at the previous level or not.\n for (int i = 0; i < sz; i++) {\n\n for (char ch = \'a\'; ch <= \'z\'; ch++) {\n char replacedCharArray[] = word.toCharArray();\n replacedCharArray[i] = ch;\n String replacedWord = new String(replacedCharArray);\n if (mpp.containsKey(replacedWord) &&\n mpp.get(replacedWord) + 1 == steps) {\n\n seq.add(replacedWord);\n dfs(replacedWord, seq);\n\n // pop the current word from the back of the queue\n // to traverse other possibilities.\n seq.remove(seq.size() - 1);\n }\n }\n }\n }\n public List < List < String >> findLadders(String beginWord, String endWord,\n List < String > wordList) {\n\n // Push all values of wordList into a set\n // to make deletion from it easier and in less time complexity.\n Set < String > st = new HashSet < String > ();\n int len = wordList.size();\n for (int i = 0; i < len; i++) {\n st.add(wordList.get(i));\n }\n\n // Perform BFS traversal and push the string in the queue\n // as soon as they\u2019re found in the wordList.\n Queue < String > q = new LinkedList < > ();\n b = beginWord;\n q.add(beginWord);\n mpp = new HashMap < > ();\n\n // beginWord initialised with level 1.\n mpp.put(beginWord, 1);\n int sizee = beginWord.length();\n st.remove(beginWord);\n while (!q.isEmpty()) {\n String word = q.peek();\n int steps = mpp.get(word);\n q.remove();\n\n // Break out if the word matches the endWord.\n if (word.equals(endWord)) break;\n\n // Replace each character of the word with letters from a-z \n // and check whether the transformed word is present in the \n // wordList or not, if yes then push to queue\n for (int i = 0; i < sizee; i++) {\n\n for (char ch = \'a\'; ch <= \'z\'; ch++) {\n char replacedCharArray[] = word.toCharArray();\n replacedCharArray[i] = ch;\n String replacedWord = new String(replacedCharArray);\n if (st.contains(replacedWord) == true) {\n q.add(replacedWord);\n st.remove(replacedWord);\n\n // push the word along with its level\n // in the map data structure.\n mpp.put(replacedWord, steps + 1);\n }\n }\n\n\n }\n }\n ans = new ArrayList < > ();\n\n // If we reach the endWord, we stop and move to step-2\n // that is to perform reverse dfs traversal.\n if (mpp.containsKey(endWord) == true) {\n List < String > seq = new ArrayList < > ();\n seq.add(endWord);\n dfs(endWord, seq);\n }\n return ans;\n }\n}\n``` | 5 | 1 | ['Hash Table', 'String', 'Breadth-First Search', 'Java'] | 0 |
word-ladder-ii | Word Ladder II: Finding All Shortest Transformation Sequences | word-ladder-ii-finding-all-shortest-tran-piuz | Intuition\nThis problem requires finding all the shortest transformation sequences from the beginWord to the endWord using a word list wordList, where each tran | sameershreyas13 | NORMAL | 2023-07-24T06:01:56.300808+00:00 | 2023-07-24T06:59:42.244962+00:00 | 1,140 | false | # Intuition\nThis problem requires finding all the shortest transformation sequences from the beginWord to the endWord using a word list wordList, where each transformation must change exactly one letter.\n\n# Approach Overview:\nTo solve the problem, we employ a combination of Breadth-First Search (BFS) and Depth-First Search (DFS).\n\n# Breadth-First Search (BFS):\nWe start by performing a BFS from the beginWord to find the shortest distance (minimum number of transformations) from the beginWord to each word in the wordList. This step ensures that we obtain the shortest transformation sequence for each word.\n\n# Backtracking with Depth-First Search (DFS):\nAfter obtaining the shortest distances using BFS, we initiate a DFS to backtrack and find all possible transformation sequences. This allows us to enumerate all valid paths that lead from the beginWord to the endWord.\n\n# Implementation Details:\nIn our implementation, we use an unordered_map mpp to store the word distances, a queue for BFS, and a vector ans to store the final transformation sequences.\n\n# Complexity Analysis:\nThe BFS phase takes O(N * L) time, where N is the number of words in wordList and L is the average word length. The DFS phase contributes to the overall complexity as well.\n\n# Code\n```\nclass Solution {\n vector<vector<string>> ans;\n unordered_map<string, int> mpp;\n void dfs(vector<string> v, string beginWord){\n string last = v[v.size() - 1];\n if(last == beginWord){\n reverse(v.begin(), v.end());\n ans.push_back(v);\n return;\n }\n int lev = mpp[last];\n for(int i = 0; i < last.size(); i++){\n char org = last[i];\n for(char c = \'a\'; c <= \'z\'; c++){\n last[i] = c;\n if(mpp.count(last) && mpp[last] + 1 == lev){\n v.push_back(last);\n dfs(v, beginWord);\n v.pop_back();\n }\n }\n last[i] = org;\n }\n }\npublic:\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n mpp.clear();\n ans.clear();\n unordered_set<string> s;\n for(auto& it : wordList)s.insert(it);\n queue<string> q;\n q.push(beginWord);\n if(s.find(beginWord) != s.end())s.erase(beginWord);\n if(s.find(endWord) == s.end())return {};\n int dis = 0;\n while(!q.empty()){\n int sz = q.size();\n while(sz--){\n string temp = q.front();\n q.pop();\n mpp[temp] = dis;\n if(temp == endWord)goto label;\n for(int i = 0; i < temp.size(); i++){\n char org = temp[i];\n for(char c = \'a\'; c <= \'z\'; c++){\n temp[i] = c;\n if(s.find(temp) != s.end()){\n s.erase(temp);\n q.push(temp);\n }\n }\n temp[i] = org;\n }\n }\n dis++;\n }\n label:\n vector<string> v = {endWord};\n dfs(v, beginWord);\n return ans;\n }\n};\n``` | 5 | 0 | ['Backtracking', 'Breadth-First Search', 'Graph', 'C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.