Uber | L4 | Phone interview SDE | USA
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2021-08-25Added By Anonymous
Source: Link
Company: Uber
Role: software engineer ii
Interview Stage: Phone Screen
Location: USA
Original Post Content:
Question:
Given path to file or directory. Assume all are text.
Implement Iterator which transverses over all the words in the file.
My Solution: Didn't get time to complete the whole solution but I explained the interviewer the approach. Is it the right way to implement an iterator?
1public class DesignIterator {
2
3 static List<String> words = new ArrayList<>();
4
5 public static void buildWords(String line) {
6
7 String output ="";
8
9 for(char c: line.toCharArray()) {
10
11 if(c==' ' && !output.isEmpty()) {
12 words.add(output);
13 output = "";
14 continue;
15 }
16 else if(c!=' ') {
17 output+=c;
18 }
19
20
21 }
22
23 if(!output.isEmpty()) {
24 words.add(output);
25 }
26
27
28 }
29
30
31 public static void main(String[] args) {
32
33 try {
34 BufferedReader br = new BufferedReader(new FileReader("resources/File.txt"));
35
36 String content = br.readLine();
37
38 while(content!=null) {
39 buildWords(content);
40 content = br.readLine();
41 }
42
43
44 } catch (FileNotFoundException e) {
45 e.printStackTrace();
46 } catch (IOException io) {
47 io.printStackTrace();
48 }
49
50 //System.out.println(words);
51 List<Iterator> input= new ArrayList<>();
52 input.add(words.iterator());
53
54 WordIterator iterateWords = new WordIterator(input);
55 System.out.println(iterateWords.next());
56 System.out.println(iterateWords.next());
57 System.out.println(iterateWords.next());
58 System.out.println(iterateWords.next());
59 System.out.println(iterateWords.next());
60 System.out.println(iterateWords.next());
61 System.out.println(iterateWords.next());
62 System.out.println(iterateWords.next());
63 System.out.println(iterateWords.next());
64 System.out.println(iterateWords.next());
65 System.out.println(iterateWords.next());
66
67 }
68 }
69
70
71 public class WordIterator {
72
73 List<Iterator> wordsList;
74 int count = 0;
75 int size=0;
76
77 public WordIterator(List<Iterator> words) {
78 this.wordsList=words;
79 size = wordsList.size();
80 }
81
82 public Object next() {
83
84 if(wordsList!=null) {
85
86 Iterator itr = wordsList.get(count % size);
87 if(itr.hasNext()) {
88 return itr.next();
89 }
90 }
91 return null;
92
93 }
94
95}