Walmart Labs Interview Question
Software DevelopersTeam: Customer experience
Country: United States
Interview Type: In-Person
This was a very hard one for me to make it.
Actually I though of a recursive version with is n^n but then looking a bit closer I though that this is better to do using a graph algorithm which creating the graph would be n^2 and traversing it would be n using a BFS traversal.
public static bool PathExist(List<string> set, string start, string end)
{
if(string.IsNullOrEmpty(start) ||
string.IsNullOrEmpty(end) ||
start.Length != end.Length
{
throw new ArgumentException();
}
// Sanitize the set
var hs = new HashSet<string>();
foreach(string s in set)
{
if(s.Length == start.Length)
{
// Hashset ignores if is already there
hs.Add(s);
}
}
// Building graph in n^2
hs.Add(start);
hs.Add(end);
var graph = Dictionary<string, HashSet<string>>();
foreach(var t1 in hs)
{
foreach(var t2 in hs)
{
if(IsOneLetterDiff(t1, t2))
{
if(!graph.ContainsKey(t1))
{
graph.Add(t1, new List<string>() { t2 });
}
else
{
graph[t1].Add(t2);
}
}
}
}
// Now BFS traverse of the graph to find if a path exist
var q = Queue<string>();
var visited = new HashSet<string>();
q.Enqueue(start);
while(q.Count > 0)
{
string cur = q.Dequeue();
// Found a path
if(cur == end)
return true;
if(!visited.Contains(cur))
{
visited.Add(cur);
if(graph.ContainsKey(cur))
{
foreach(var child in graph[cur])
{
q.Enqueue(child);
}
}
}
}
return false;
}
// Assumes that their both non-null and with the same length
private static bool IsOneLetterDiff(string one, string two)
{
bool found = false;
for(int i = 0; i < one.Length; i++)
{
if(one[i] != two[i])
{
if(!found)
{
found == true;
}
else
{
return false;
}
}
return found;
}
}
A very simple Java logic
import java.util.ArrayList;
public class StartEndSetString {
private boolean getPaths(String start, String end, List<String> data) {
if(string_diff(start, end)==1){
return true;
}
Iterator<String> iterator = data.iterator();
while(iterator.hasNext()){
String values = iterator.next();
if(string_diff(values, start)==1){
iterator.remove();
if(getPaths(values, end, data)){
return true;
}
}
}
return false;
}
private int string_diff(String start, String end) {
int diff = 0;
for(int i=0;i<start.length();i++){
if(start.charAt(i)!=end.charAt(i)){
diff+=1;
}
}
return diff;
}
}
A very simple Java code
public class StartEndSetString {
private boolean getPaths(String start, String end, List<String> data) {
if(string_diff(start, end)==1){
return true;
}
Iterator<String> iterator = data.iterator();
while(iterator.hasNext()){
String values = iterator.next();
if(string_diff(values, start)==1){
iterator.remove();
if(getPaths(values, end, data)){
return true;
}
}
}
return false;
}
private int string_diff(String start, String end) {
int diff = 0;
for(int i=0;i<start.length();i++){
if(start.charAt(i)!=end.charAt(i)){
diff+=1;
}
}
return diff;
}
}
import collections
graph = collections.defaultdict(set)
valid_path = []
def find_path(array, start, end):
array = [start] + array + [end]
for path in array:
if len(path) != len(end): continue
graph[path] = set()
valid_path.append(path)
for node1 in valid_path:
c0 = collections.Counter(node1)
for node2 in valid_path:
if node1 == node2: continue
c1 = collections.Counter(node2)
diff = c0 - c1
if len(list(diff.elements()))==1:
graph[node1].add(node2)
graph[node2].add(node1)
# for g in graph:
# print g, " :", graph[g]
visited = []
queue = [start]
while queue:
u = queue.pop(0)
if u in visited: continue
if u==end: return True
visited.append(u)
for adj in graph[u]:
if adj not in visited:
queue.append(adj)
return False
It's more efficient to work backwards from the end string.
1. Eliminate words that are not the same length as the end word
2. Find words that differ by one char from end string, and remove these matched
words from search
3. Repeat (2) where end string becomes a matched word.
Linear time O(n^2). Space: O(1)
Ruby impl. Running time O(nm). Space: O(1).
require 'set'
def exists_path?(start_str='',end_str='',str_set=Set.new)
return true if start_str == end_str || strings_diff_by_one?(start_str, end_str)
return false if start_str.length != end_str.length
original_end_str=end_str
path=[end_str]
str_set.add(start_str)
while str_set.length > 0 && start_str != end_str &&
(found_str = find_str_with_diff_one(str_set,end_str))
str_set.delete(found_str)
end_str = found_str
path.insert(0,end_str)
end
path.length>=2 && path[0]==start_str && path[path.length-1]==original_end_str
end
def strings_diff_by_one?(string1,string2)
chars_changed=0
string1.chars.each_with_index do |character,index|
#puts "#{character} - #{str_value[index]}"
if character != string2[index]
chars_changed+=1
end
end
chars_changed==1
end
def find_str_with_diff_one(str_set, str_value)
return nil if str_set.empty? || str_value.to_s.length==0
found_str=nil
str_set.each do |str|
found_str=str if strings_diff_by_one?(str,str_value)
end
return found_str
end
start_str='cog'
end_str='bad'
puts "path exists?: #{exists_path?(start_str,end_str,Set.new(['bag', 'cag','cat', 'fag','con','rat','sat','fog']))}"
Can be modeled as a graph problem. Let the vertex be the set of all words that are given to us, including the start and end words.
- Praveen Ram C June 23, 2015Now, for each vertex, there exists an edge if a vertex can be converted to another vertex.
So, lets say we have "dog" and "cog". Since dog can be converted to cog by replacing one character, we ad an edge between them.
Once we are done constructing the graph, all we have to do is do a BFS between the start node and end node which also gives us the shortest path.