Google Interview Question for Software Engineers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
1
of 1 vote

public static int getPathLength(String s) {
        String[] lines = s.split("\n");
        int i = 0, len = s.length(), res = 0;
        Stack<Integer> stack = new Stack<Integer>();
        Stack<Boolean> added = new Stack<Boolean>();
        stack.push(0);
        added.push(true);
        int prevSpaces = -1;
        for(i = 0; i < len; i++) {
            int spaces = lines[i].trim().length() - lines[i].length();

            if(spaces < prevSpaces) {
                while (spaces < prevSpaces) {
                    stack.pop();
                    added.pop();
                    prevSpaces--;
                }
            }
            if(lines[i].contains(".")) {
                if(isPic(lines[i]) && !added.peek()) {//0 ,    //true   //prev = 1 ,sp = 0     //res = 4
                    res += stack.peek();
                    added.pop();
                    added.push(true);
                }
            } else {
                if(spaces <= prevSpaces) {
                    stack.pop();
                    added.pop();
                } else prevSpaces++;
                stack.push(stack.peek() + lines[i].trim().length() + 1);
                added.push(false);
            }
        }
        return res;
    }



    public static boolean isPic(String f) {
        String appendix = f.substring(f.length() - 4);
        if(appendix.equals(".gif") || appendix.equals(".jpg") || appendix.equals(".png")) return true;
        return false;
    }

Looking for interview questions sharing and mentors? Visit A++ Coding Bootcamp at aonecode.com (select english at the top right corner).
We provide ONE TO ONE courses that cover everything in an interview from the latest interview questions, coding, algorithms, system design to mock interviews. All classes are given by experienced engineers/interviewers from FB, Google and Uber. Help you close the gap between school and work. Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us with any questions.

- aonecoding January 15, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Great solution, thanks. IMHO, it is worth handling directories explicitly (starts with "/"), otherwise code might return directory "/allimages.jpg", for example.

- Johnny January 16, 2017 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

$ find / -type f \( -name "*.jpg" -o -name "*.png" -o -name "*.gif" \)

- srterpe January 17, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is the basic idea, observe the nested functions ( ZoomBA ) :

def find_all_pic_dir(dir='.', 
          pic_extensions=set('.jpg', '.png' , '.gif') ){
  // nest it 
  def recurse(cur_dir){
    d = file ( cur_dir )
    if ( !d.file.directory ) return 
    pic_dir = exists ( d ) :: { file($.o).extension.toLowerCase @ pic_extensions }
    if ( pic_dir ){ dir_paths += cur_dir }
    for ( child : d ){
      recurse( child.canonicalPath )
    }
  }
  // set up and call 
  dir_paths = set()
  recurse( file(dir).file.canonicalPath )
  // return 
  return dir_paths
}

dirs = find_all_pic_dir ( "/" )
println( dirs )

- NoOne January 15, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We don't need to keep track of multiple directories at the same level.

public List<String> getImageFilePaths(String fileName) throws Exception{
        List<String> finalList = new ArrayList();
        BufferedReader br = new BufferedReader(new FileReader(fileName));

        String line = br.readLine();

        Map<Integer, String> values = new HashMap();

        while (line != null) {
            int whitespaceCount = line.length() - line.trim().length();
            if (whitespaceCount == 0) {
                values = new HashMap();
                values.put(0, line);
            } else {
                int tabCount = whitespaceCount/4;
                line = line.trim();

                if(line.startsWith("/")) {
                    values.put(tabCount, line);
                } else if(line.endsWith(".gif") || line.endsWith(".jpg") || line.endsWith(".png")) {
                    StringBuilder sb = new StringBuilder();

                    for(int i=0;i<tabCount;i++) {
                        sb.append(values.get(i));
                    }

                    finalList.add(sb.toString());
                }
            }
            line = br.readLine();
        }
        return finalList;
    }

- Hokage January 16, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#TODO : Add validation for error scenarios

private static readonly int MaxPathsAllowed = 256;
        private static readonly char PathSeparator = '/';
        private static string[] directoryTokens = new string[MaxPathsAllowed];
        private static int currentDirectoryIndex = -1;

        private static void ProcessFile(string fileName)
        {
            foreach (var line in File.ReadAllLines(fileName))
            {
                ProcessLine(line);
            }
        }
        private static void ProcessLine(string line)
        {
            int localTabCount = -1;
            while (line[++localTabCount] == '\t') ;
            var name = line.TrimStart('\t');
            if (IsDirectory(name))
            {
                directoryTokens[localTabCount] = name;
                currentDirectoryIndex = localTabCount;
            } else if (IsImage(name))
            {
                PrintPath(name);
            }
        }

        private static void PrintPath(string name)
        {
            PrintPath(name, directoryTokens, currentDirectoryIndex, PathSeparator);
        }

        private static void PrintPath(string name, string[] paramDirectoryTokens, int tabIndex, char separator)
        {
            var result = string.Empty;

            for (int index = 0; index <= tabIndex; index++)
            {
                result += paramDirectoryTokens[index];
            }
            result += PathSeparator + name;
            Console.WriteLine(result);
        }

        private static string[] imagePathExtensions = new string[] { ".img", ".png", ".jpg" };
        private static bool IsImage(string name)
        {
            var result = false;
            int index = name.LastIndexOf('.');
            if (index != -1)
            {
                return imagePathExtensions.Contains(name.Substring(index));
            }
            return result;
        }

        private static bool IsDirectory(string name)
        {
            return name[0] == PathSeparator;
        }

- ankushbindlish January 17, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;
public class AbsolutePathImageDirectory {

  HashSet<Node> set;
  Node root;

  public static void main(String[] args) {
    AbsolutePathImageDirectory apid = new AbsolutePathImageDirectory();
    System.out.println("(1) First approach using Brute Force");
    apid.printAbsolutePath(new String[] {
      "/usr",
      "  /local",
      "    profile.jpg",
      "    /bin",
      "      config.txt",
      "      dest.png",
      "    /rbin",
      "  img.gif",
      "/sys",
      "  /re",
      "  /tmp",
      "    pic.jpg"
      }
    );
    System.out.println("\n(2) Second approach using Trees");
    apid.add(new String[] {
      "/usr",
      "  /local",
      "    profile.jpg",
      "    /bin",
      "      config.txt",
      "      dest.png",
      "    /rbin",
      "  img.gif",
      "/sys",
      "  /re",
      "  /tmp",
      "    pic.jpg"
      }
    );
    System.out.println(Arrays.toString(apid.getAbsolutePath()));
  }

  public void printAbsolutePath(String[] inputs) {
    for(int i = 0; i < inputs.length; i++) {
      if(isImage(inputs[i])) {
        int imageIndentCount = inputs[i].length()-inputs[i].replace(" ", "").length();
        StringBuilder sb = new StringBuilder();
        for(int j = i; j >= 0; j--) {
          if(inputs[j].contains("/")) {
            int indent = inputs[j].length()-inputs[j].replace(" ", "").length();
            if(indent+2 == imageIndentCount) {
              sb.insert(0,inputs[j].replace(" ",""));
              imageIndentCount -= 2;
            }
          }
        }
        System.out.println(sb.toString());
      }
    }
  }

  public AbsolutePathImageDirectory() {
    set = new HashSet<Node>();
    root = new Node(null, "");
  }

  public void add(String[] inputs) {
    // indent == 2 spaces
    Node current = root;
    int prevIndentCount = -2;
    for(int i = 0; i < inputs.length; i++) {
      int currentIndentCount = inputs[i].length()-inputs[i].replace(" ", "").length();
      int difference = prevIndentCount-currentIndentCount+2;
      System.out.println(inputs[i]+" "+currentIndentCount+" "+difference);
      if(difference > 0) {
        for(int j = 0; j < difference/2; j++) {
          current = current.parent;
        }
      }
      if(!isImage(inputs[i])) {
        Node n = new Node(current, inputs[i].replace(" ", ""));
        current.children.put(n.name, n);
        current = n;
      } else {
        set.add(current);
        currentIndentCount -= 2;
      }
      prevIndentCount = currentIndentCount;
    }
  }

  public String[] getAbsolutePath() {
    String[] result = new String[set.size()];
    int index = 0;
    for(Node n : set) {
      StringBuilder sb = new StringBuilder();
      while(n.parent != null) {
        sb.insert(0, n.name);
        n = n.parent;
      }
      result[index] = sb.toString();
      index++;
    }
    return result;
  }

  public boolean isImage(String s) {
    return s.contains(".png") ||
      s.contains(".gif") ||
      s.contains(".jpg") ||
      s.contains(".jpeg");
  }

  public class Node {
    HashMap<String, Node> children;
    Node parent;
    String name;
    public Node(Node parent, String name) {
      this.parent = parent;
      this.children = new HashMap<>();
      this.name = name;
    }
  }
}

- obed.tandadjaja February 01, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More