Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
1,046 views
in Online Assessments by Expert (46,090 points) | 1,046 views

6 Answers

0 like 0 dislike
Best answer

I got this question in a codility test. Panicked and wasnt able to solve. Any ideas ?

 

You are given a string containing a detailed list of files. Your task is to evaluate a simple query on a certain subset of these files.

 

The string consists of N lines separated by end-of-line characters ( ASCII code 10). Each line contains information about one file, grouped in five columns: owner, perm, date, size and name(in that order). The columsns (except for the last one ) have fixed lengths and are separated by one space. They have the following meanings and format

 

  •  

    Column perm has length 3 and contains info about permissions. It contains 3 characters: They control respectively whether reading, writing & execution of the file is permitted.The chars are respectively r, w & x if these operations are permitted; otherwise they are -.

     

  •  

    Column owner has length 6 & contains a string representing the name of the user who created the file. The name is case sensitive and aligned to the left.

     

  •  

    Colum size has a length of 10 & contains the size of the file in bytes. the size is less than 2^31 bytes and is aligned to the right.

     

  •  

    Colum date has length 11 & contains the last modified date of the file in the format ''dd MMM YYYY''. The names of the months are Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov & Dec

     

  •  

    Column name is of variable length and contains the name of the file. The name of the file consists of at most 255 printable ASCII chars and contains at least one dot character.

     

 

We are only interested in files that satisy:

 

  • Files that are executable aka files with permission to execute
  • They were created by the user admin
  • Their size is less 14 * 2 ^ 20 bytes

 

Calculate the earliest last modification date of these files.

 

Write a function that given a strig describing the file list, returns the answer to the query, encoded as a string. Date should be returned in the format ''dd MMM yyyy'

 

If there are no such files return NO FILES

 

For example, given string S with N = 8 lines (enclosed between """):

 

"""
admin -wx 29 Sep 1983        833 source.h
admin r-x 23 Jun 2003     854016 blockbuster.mpeg
admin --x 02 Jul 1997        821 delete-this.py
admin -w- 15 Feb 1971      23522 library.dll
admin --x 15 May 1979  645922816 logs.zip
jane  --x 04 Dec 2010      93184 old-photos.rar
jane  -w- 08 Feb 1982  681574400 important.java
admin rwx 26 Dec 1952   14680064 to-do-list.txt
"""

 

The function should return "29 Sep 1983"

 

Assume that:

 

  • N is an integer within the range [1 - 100]
  • String s contains only of printable ASCII chars and EoL character
  • String S is a correct list of files according to the specs above. Files can have the same names.
by Expert (46,090 points)
0 like 0 dislike
package Misc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MicrosoftCodility {
    private static final long LIMIT = (long)(14 * Math.pow(2, 20));

    public static void main(String[] args) {
        MicrosoftCodility mc = new MicrosoftCodility();
        String file = "admin -wx 29 Sep 1983        833 source.h\nadmin r-x 23 Jun 2003     854016 blockbuster.mpeg\nadmin --x 02 Jul 1997        821 delete-this.py\n"
            + "admin -w- 15 Feb 1971      23522 library.dll\nadmin --x 15 May 1979  645922816 logs.zip\njane  --x 04 Dec 2010      93184 old-photos.rar\njane  -w- 08 Feb 1982  681574400 important.java\n"
            + "admin rwx 26 Dec 1952   14680064 to-do-list.txt\n";

       String res = mc.microsoftFileAdmin(file);

        if(res.length() == 0) {
            System.out.println("No Files!");
        } else {
            System.out.println(res);
        }
    }

    public String microsoftFileAdmin(String files) {
        if(files == null || files.length() == 0 ) {
            return "";
        }

        String[]fileGroup = files.split("\n");
        if(fileGroup.length < 1 || fileGroup.length > 100) {
            return "";
        }

        List<String> result = new ArrayList<>();

        for(String file : fileGroup) {
            file = file.replaceAll("\\s{2,}", " ");
            String[] curFile = file.split(" ");
            if(valid(curFile)) {
                StringBuilder sb = new StringBuilder();
                for(int j = 2; j <= 4; j++) {
                    sb.append(curFile[j]);
                    sb.append(" ");
                }
                result.add(sb.toString().trim());
            }
        }

        if(result.size() > 1) {
            Collections.sort(result, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return Integer.parseInt(o1.split(" ")[2]) - Integer.parseInt(o2.split(" ")[2]);
                }
            });
        }
        return result.get(0);
    }

    private boolean valid(String[] curFile) {
        return curFile[0].equals("admin") && curFile[1].contains("x") && Long.parseLong(curFile[5]) < LIMIT;
    }
}
by Expert (46,090 points)
0 like 0 dislike
public class StringFilesProcess {
    public static void main(String[] args) {
        String str = "admin -wx 29 Sep 1983        833 source.h\n"+
                "admin r-x 23 Jun 2003     854016 blockbuster.mpeg\n"+
                "admin --x 02 Jul 1997        821 delete-this.py\n"+
                "admin -w- 15 Feb 1971      23522 library.dll\n"+
                "admin --x 15 May 1979  645922816 logs.zip\n"+
                "jane  --x 04 Dec 2010      93184 old-photos.rar\n"+
                "jane  -w- 08 Feb 1982  681574400 important.java\n"+
                "admin rwx 26 Dec 1952   14680064 to-do-list.txt";

        Map<String, String> months  = new HashMap<String, String>() {{
            put("Jan", "01");put("Feb", "02");put("Mar", "03");put("Apr", "04");put("May", "05");put("Jun", "06");
            put("Jul", "07");put("Aug", "08");put("Sep", "09");put("Oct", "10");put("Nov", "11");put("Dec", "12");
        }};
        String[] rows = str.split("\n");
        int limit = 14 * (int)(Math.pow(2, 20));
        int oldest = Integer.MAX_VALUE;
        String ans="";
        for (String row : rows) {
            String[] columns = row.split("\\s+",-2);
            if(!columns[1].contains("x")){
                continue;
            }
            if(!columns[0].equals("admin")){
                continue;
            }
            int size = Integer.parseInt(columns[5]);
            if(limit <= size){
                continue;
            }
            int curDate = Integer.parseInt(columns[4]+months.get(columns[3])+columns[2]);
            if(oldest >= curDate){
                oldest =curDate;
                ans = columns[4]+" "+columns[3]+" "+columns[2];
            }
        }
        System.out.println(ans);
    }
}
by Expert (46,090 points)
0 like 0 dislike
my try ...
string AceptableFiles(string s)
{
    struct info
    {
        string user;
        string perm;
        string dd;
        string mmm;
        string yyyy;
        size_t size;
        string filename;
    };

    vector<info> infos;
    stringstream ss(s);
    string str;
    while (getline(ss, str, '\n'))
    {
        info curinfo;
        stringstream s1(str);
        s1 >> curinfo.user >> curinfo.perm >> curinfo.dd >> curinfo.mmm >> curinfo.yyyy >> curinfo.size >> curinfo.filename;
        infos.push_back(curinfo);
    }

    vector<info> filesAccepted;
    for (size_t i = 0; i < infos.size(); i++)
    {
        if (infos[i].perm.find('x') != string::npos && infos[i].user.find("admin") != string::npos && infos[i].size < 14 * pow(2, 20))
        {
            filesAccepted.push_back(infos[i]);
        }
    }

    if (filesAccepted.size() == 0)
    {
        return "NO FILES";
    }

    int minTime = INT64_MAX;
    int minIndex = INT64_MAX;
    for (size_t i = 0; i < filesAccepted.size(); i++)
    {
        size_t dd = atoi(filesAccepted[i].dd.c_str());
        dd += atoi(filesAccepted[i].mmm.c_str())*31;
        dd += atoi(filesAccepted[i].yyyy.c_str())*365;

        if (minTime > dd)
        {
            minTime = dd;
            minIndex = i;
        }
    }

    return filesAccepted[minIndex].dd + " " + filesAccepted[minIndex].mmm + " " + filesAccepted[minIndex].yyyy;
}
by Expert (46,090 points)
0 like 0 dislike

My attempt to solve this..
https://leetcode.com/playground/D3PWVphP

 

import java.io.*;
import java.text.*;
import java.util.Date;

// "static void main" must be defined in a public class.
public class Main {
     private static int limit = (int) (14 * Math.pow(2, 20));
    public static void main(String[] args) throws ParseException, Exception{
        String str = "admin -wx 29 Sep 1983        833 source.h\n"+
                "admin r-x 23 Jun 2003     854016 blockbuster.mpeg\n"+
                "admin --x 02 Jul 1997        821 delete-this.py\n"+
                "admin -w- 15 Feb 1971      23522 library.dll\n"+
                "admin --x 15 May 1979  645922816 logs.zip\n"+
                "jane  --x 04 Dec 2010      93184 old-photos.rar\n"+
                "jane  -w- 08 Feb 1982  681574400 important.java\n"+
                "admin rwx 26 Dec 1952   14680064 to-do-list.txt";

          // str = "admin -wx 29 Sep 1983        833 source.h\n"+
          //       "admin r-x 23 Jun 2003     854016 blockbuster.mpeg\n"+
          //       "admin --x 02 Jul 1997        821 delete-this.py\n"+
          //       "admin -wx 15 Feb 1971      23522 library.dll\n"+
          //       "admin --x 15 May 1979  645922816 logs.zip\n"+
          //       "jane  --x 04 Dec 2010      93184 old-photos.rar\n"+
          //       "jane  -wx 08 Feb 1982  681574400 important.java\n"+
          //       "admin rwx 26 Dec 1970   5988 to-do-list.txt";
        System.out.println(getLatestModifedFile(str));
    }

    private static String getLatestModifedFile(String str) throws ParseException, Exception {
        String ret = null;
        Reader rd = new StringReader(str);
        BufferedReader br = new BufferedReader(rd);
        String line;
        PriorityQueue<String> pq = new PriorityQueue<>((a, b) -> {
            SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
            Date dateA = null;
            Date dateB = null;
            try {
                dateA = sdf.parse(a);
                dateB = sdf.parse(b);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            return Objects.compare(dateA, dateB, Date::compareTo);
        });
        while ((line = br.readLine()) != null) {
            line = line.replaceAll("\\s+", " ");
            String[] fileDetails = line.split(" ");
            for (int i = 0; i < fileDetails.length; i++) {
                fileDetails[i] = fileDetails[i].trim();
            }

            if (fileDetails[0].equals("admin") && fileDetails[1].contains("x") && Integer.parseInt(fileDetails[5]) < limit) {
                pq.add(fileDetails[2] + " " + fileDetails[3] + " "+ fileDetails[4]);
            }
        }
        return pq.size() == 0 ? "NO FILES" : pq.peek();
    }
}
by Expert (46,090 points)
0 like 0 dislike

6-7 lines of python code. You need a reverse map at the end to convert monthNum to month but was too lazy to type that one out. You can also improve time complexity by keeping 1 tuple of possibilities and always checking/replacing it when you encounter a new possibility.

 

monthMap = {"Jan": 0, "Feb": 1, "Mar": 2, "Apr": 3, "May": 4, "Jun": 5, "Jul": 6, "Aug": 7, "Sep": 8, "Oct": 9,
            "Nov": 10, "Dec": 11}
possibilities = []
for line in string.strip().split("\n"):
    user, perms, day, month, year, size, _ = line.split()
    if "x" not in perms: continue
    if "admin" != user: continue
    if int(size) >= 4 * (2 ** 20): continue
    possibilities.append([year, monthMap[month], day])

print(sorted(possibilities)[0])
by Expert (46,090 points)