Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Disheartened

Options
24

Comments

  • Moderators, Education Moderators, Technology & Internet Moderators Posts: 35,049 Mod ✭✭✭✭AlmightyCushion


    accensi0n wrote: »
    I don't work in development or a coding role.
    This is what I'd naively do in python (Done quickly with not much thought put in):
    I've probably missed something obvious.
    num = [0,0,2,2,5,6]
    num.sort()
    hour = str(num[0]) + str(num[1])
    min = str(num[2]) + str(num[3])
    sec = str(num[4]) + str(num[5])
    
    if int(hour) > 23:
        print("Time not possible from those numbers - hour problem")
    elif int(min) > 59:
        print("Time not possible from those numbers - minute problem")
    elif  int(sec) > 59:
        print("Time not possible from those numbers - second problem")
    else:
        print(hour + ":" + min + ":" + sec)
    

    That wouldn't work for 0,0,0,7,8,9. It would say the time is not possible when it is. 07:08:09


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    Seamus wrote:
    Now you don't need to loop through the input array a number of times, you only need to loop once.

    You've just unrolled a small loop there, many if not most optimizing compilers will do this for you already.
    However, the big bottleneck in the above code is sorting the input to begin with

    Sorting single digit numbers is an O(n) counting sort, so not actually a bottleneck in this case

    Edit: Quoted post vanished!


  • Registered Users Posts: 1,445 ✭✭✭Anjobe


    smacl wrote: »
    You've just unrolled a small loop there, many if not most optimizing compilers will do this for you already.



    Sorting single digit numbers is an O(n) counting sort, so not actually a bottleneck in this case

    Edit: Quoted post vanished!

    I don't think it worked!


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    Anjobe wrote: »
    I don't think it worked!

    Possibly not, but I think the principle that you can often invest more time to get a better performance holds well enough.


  • Registered Users Posts: 793 ✭✭✭ImARebel


    seamus wrote: »
    Collaborative coding tests are the interview method du jour. Virtually every role that has even a touch of coding in it, is now using some form of coding challenge in the interview process.

    They're mainly looking for the approach to the problem and the ability of the programmer to at least understand how to make their code faster and more reliable.

    Especially if you're going for "prestige" jobs in a big modern company (Google, Amazon, Facebook, etc), they're not just looking for programmers who can bang out working code by plugging frameworks together, they want programmers who understand how to design algorithms from the ground up and who have some semblance of understanding about performance, about sizes of data types, etc.

    This isn't a kind of wankey elitism. In the past when all software was something you deployed on-prem, then Oracle or whoever could get away with slow code and crap algorithms by just telling their customers to buy more hardware.

    In the new world of SaaS, all customers are equal, so you can't cover up ****ty code by loading the cost of it onto your customer. An algorithm that's half as fast, costs twice as much. So a programmer who understands why it matters whether an algorithm / data type is O(1), O(n), O(log n), etc., is less likely to take your system down than one who just loads a 2GB file into a variable and does a regex match on it.

    Of course, as you say, it does depend on the coder and their domain. If your expertise and interests are in coding integrations between systems, especially data exchange across networks, then there's a good chance that code performance is never going to be a significant factor given the relative slowness of the data interchange.

    For the OP, this isn't a difficult problem, but one I would have thought a bit on the "lateral thinking" side for a grad straight out of college. Definitely stick with the coding practice sites, and maybe get yourself a refresher book on the data structures and algorithms. My experience of college is that they flew through the theory in year one and then you never saw them again, everything else was practical coding.

    i totally get your point and I agree the likes of Google and Amazon do expect that sort of knowledge.

    But the OP was feeling disheartened, I was just saying there is life beyond algorithms if they aren't his thing. I was just giving a different view point.


  • Advertisement
  • Registered Users Posts: 793 ✭✭✭ImARebel


    beauf wrote: »
    Converting or validating time/date, numbers especially from legacy systems, where they are strings, padded with spaces or unknown non visible characters, and can be different lengths, is pretty common for me.

    I actually enjoy solving these kind of problems more than just routine work. But I've never done them in a interview situation.

    yeah me too but no one has ever pulled a random set of 6 digits from a DB and asked me to make a time out of it

    it already is a time, albeit in whatever format and you're then transforming that data. I do plenty of that too

    I just don't conjure up time out of a set of numbers someone has plucked out of their ass, the data I work with has meaning. there's only so many ways hr:mm:ss can be stored in any DB whether legacy or otherwise. i'm yet to see 1:05am in the morning being recorded as {1,2,0,5,9,7} (or whatever) and I've to deduce it from a set of 6 numbers

    I was just giving a point of view that if algorithms aren't his thing there are other skillsets out there being utilised by coders everywhere.


  • Registered Users Posts: 1,445 ✭✭✭Anjobe


    smacl wrote: »
    Possibly not, but I think the principle that you can often invest more time to get a better performance holds well enough.

    Of course that's true, however I think this exercise was more to test the candidate's ability to analyse a problem and design an algorithm to solve it. There is not much point spending time optimising code for performance if you don't understand what it does and break the functionality.


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    Anjobe wrote: »
    Of course that's true, however I think this exercise was more to test the candidate's ability to analyse a problem and design an algorithm to solve it. There is not much point spending time optimising code for performance if you don't understand what it does and break the functionality.

    Very true, but if the OP were to come up with an overly slow brute force solution they'd likely get marked down for it.


  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    smacl wrote: »
    Edit: Quoted post vanished!
    Anjobe wrote: »
    I don't think it worked!
    Nope! :D

    It would have nearly worked, but nearly isn't good enough. I was too focussed on on the array specifics, I missed the edge case.


  • Closed Accounts Posts: 1,758 ✭✭✭Pelvis


    Anjobe wrote: »
    This problem is not so difficult. Put the six digits into an array and sort it in ascending order then:

    1.) If the 5th digit is greater than 5 then search back through the array from index 4 until you find a number that is not greater than 5. If you find one then swap that with the 5th digit, if not then return null.

    2.) If you had to do a swap in step 1 then re-sort the first 4 digits in the array.

    3.) If the 3rd digit is greater than 5 then repeat step 1, searching back through the array from index 2.

    4.) If you had to do a swap in step 3 then re-sort the first 2 digits in the array.

    5.) If the first digit is less than 2, or the first digit == 2 and the 2nd digit is less than 4 then you have a valid time and can copy the digits in order from the array to a string, inserting ':' after digits 2&4 and return your string, otherwise return null.
    Anjobe wrote: »
    Me too! My crude solution is about 60 lines of Java, which could probably be refactored into around half that if I could be bothered!

    This sounds good! So figured I'd give it a try. Here's my effort, it seems to work well. Anyone else want to try a few more test cases to confirm?
    import java.util.Arrays;
    import java.util.HashMap;
    
    class Solution {
    
        public static String arrayToTime(int[] A) {
    
            Arrays.sort(A);
            int len = A.length;
    
            HashMap<Integer, Integer> maxNum = new HashMap<>();
            maxNum.put(0, 2);
            maxNum.put(1, 3);
            maxNum.put(2, 5);
            maxNum.put(3, 9);
            maxNum.put(4, 5);
            maxNum.put(5, 9);
    
            for (int i = len-1; i >= 0; i--){
    
                if (i == 1 && A[i] > 3 && A[i-1] == 0) break;
    
                int cur = A[i];
                if (cur <= maxNum.get(i)) continue;
                else {
                    for (int j = i-1; j >= 0; j--){
    
                        if (A[j] <= maxNum.get(i)){
                            int tmp = A[j];
                            A[j] = A[i];
                            A[i] = tmp;
                            Arrays.sort(A, 0, i);
                            break;
                        }
                    }
                }
            }
    
            if (A[0] > 2 || (A[1] > 3 && A[0] != 0 )){
                return null;
            }
    
            StringBuilder time = new StringBuilder(8);
            for (int i=0; i<A.length; i++){
                if (time.length() == 2 || time.length() == 5){
                    time.append(":");
                }
                time.append(A[i]);
            }
            return time.toString();
        }
    
        public static void main(String[] args) {
            System.out.println(arrayToTime(new int[] {0, 0, 0, 7, 8, 9}));
            System.out.println(arrayToTime(new int[] {1, 8, 3, 2, 6, 4}));
            System.out.println(arrayToTime(new int[] {2, 4, 5, 9, 5, 9}));
            System.out.println(arrayToTime(new int[] {7, 2, 4, 1, 9, 4}));
            System.out.println(arrayToTime(new int[] {8, 4, 7, 1, 8, 6}));
            System.out.println(arrayToTime(new int[] {8, 9, 0, 4, 0, 0}));
        }
    }
    

    I'm still of the opinion that this is pretty tough for an entry level graduate role!!


  • Advertisement
  • Registered Users Posts: 7,306 ✭✭✭jmcc


    Pelvis wrote: »
    The task itself was, given 6 digits, create the earliest valid time in 24-hour format, and return as a string "hr:mm:ss", or return null if it's not possible with the digits provided.

    E.g.
    0,0,0,7,8,9 would return 07:08:09
    2,4,5,9,5,9 would return null.
    If you wanted to mess with their minds, you could have asked if the digits individually represented a time. :) It could have been one of those tests to see how you think.

    Regards...jmcc


  • Registered Users Posts: 203 ✭✭Sherfin


    My attempt

    Sort numbers and place into 2 arrays
    Under6[]
    Over5[]

    If Over5.count > 2 then fail

    If (Under6[0] > 2 or Under6[1] > 3) then fail

    1st = Under6[0]
    2nd = Under6[1]
    3rd = Under6[2]
    If Over5.count > 1
    4th = Over5[1]
    else
    4th = Under6[3]
    5th = Under6[4]
    If Over5.count > 0
    6th = Over5[0]
    else
    6th = Under6[5]


  • Registered Users Posts: 7,157 ✭✭✭srsly78


    Fails because should be over4 and under5, and a bunch of other stuff :D


  • Registered Users Posts: 149 ✭✭Razzen


    try this...

    see if you can work out the logic..
    public String solve(int A, int B, int C, int D, int E, int F) {
      int[] d = {A, B, C, D, E, F};
      Arrays.sort(d);
      if (d[4] < 6) { // 2nd largest digit is smaller 6, we can just fill up
        if (10 * d[0] + d[1] < 24)
          return "" + d[0] + d[1] + ":" + d[2] + d[3] + ":" + d[4] + d[5];
        else
          return "impossible";
      } else if (d[3] < 6) { // 3rd largest digit is smaller 6, put 2nd largest in 4th position
        if (10 * d[0] + d[1] < 24)
          return "" + d[0] + d[1] + ":" + d[2] + d[4] + ":" + d[3] + d[5];
        else
          return "impossible";
      } else if (d[2] < 6) { // 4th largest digit is smaller 6, put 3rd largest in 2nd position
        if (10 * d[0] + d[3] < 24)
          return "" + d[0] + d[3] + ":" + d[1] + d[4] + ":" + d[2] + d[5];
        else
          return "impossible";
      } else {
          return "impossible";
      }
    }
    


  • Closed Accounts Posts: 1,758 ✭✭✭Pelvis


    Slightly off but still on topic. I have an opportunity to move to a dev role in my current company, it's in the early stages of an expansion and there are going to be plenty of new systems built in-house.

    One the one hand, I was kind of eager to leave once I graduated, as I've been there a long time and wanted a fresh start. On the other hand, I wouldn't have to take the wage cut I would have taken had I moved to a grad role elsewhere.

    Another con, I think, is that it's a PHP role, where as I would prefer to work with Java. I'm thinking more long term here, as don't PHP devs earn less on average? If I were to take it would I be pigeonholed as a PHP dev?


  • Closed Accounts Posts: 22,651 ✭✭✭✭beauf


    Only if you don't keep working on your skillset in other areas. Which you should.

    You get to keep your salary and do some dev work. Do other stuff on the side . I'm not seeing a downside.


  • Closed Accounts Posts: 22,651 ✭✭✭✭beauf


    ImARebel wrote: »
    yeah me too but no one has ever pulled a random set of 6 digits from a DB and asked me to make a time out of it

    ...

    Lucky you : )

    I take your point that there are lots of other development jobs. Though most programmers have a very narrow definition of what programmer is and isn't.

    Still this has been one of the more interesting threads in this forum in a while. I find the discussion from very experienced Devs interesting especially around performance.

    Where I am no one would be interested in having a discussion like and not with lesser mortals like myself.


  • Registered Users Posts: 1,029 ✭✭✭John_C


    Pelvis wrote: »
    Slightly off but still on topic. I have an opportunity to move to a dev role in my current company, it's in the early stages of an expansion and there are going to be plenty of new systems built in-house.
    In your current company you'll have domain knowledge (i.e. you know the ropes) which you won't have in a new job. That makes you more valuable than another developer with similar skills.

    My advice is to stay, assuming that you enjoy working there and that there'll be experienced developers for you to learn from.


  • Registered Users Posts: 768 ✭✭✭14ned


    smacl wrote: »
    Lets see this in six lines of C please ;)

    time_from_digits() could be compressed into less than six lines, but it's easier to read this way:
    #include <time.h>
    #include <limits.h>
    #include <stdio.h>
    
    int digit(const char *i, int limit)
    {
        int ret=(i[0]-'0')*10+(i[1]-'0');
        return (ret>=limit) ? -1 : ret;
    }
    
    const char *time_from_digits(const char *input)
    {
        struct tm t{digit(input+4, 60), digit(input+2, 60), digit(input+0, 24), 1, 1, 1970, 0, 0, 0, 0, 0};
        if(t.tm_sec<0 || t.tm_min<0 || t.tm_hour<0 || mktime(&t)<0) return "null";
        char *r=asctime(&t)+11;
        r[8]=0;
        return r;
    }
    
    int main(void)
    {
        printf("&#37;s\n", time_from_digits("122304"));
        printf("%s\n", time_from_digits("000000"));
        printf("%s\n", time_from_digits("235960"));
        printf("%s\n", time_from_digits("240100"));
        return 0;
    }
    

    Obviously this is a terrible implementation which nobody should use, but the key is to make use of the standard library functions to do the validation and printing of times. The reason we need to clamp the values by hand is because asctime() is too clever, and automagically "repairs" invalid input silently on your behalf. Any language which is not C would not do such a stupid behaviour, so the above would be much shorter and simpler on say Python, or even C++.

    You can see the above running correctly at https://wandbox.org/permlink/5p4EqctOdfFx8YAh

    Niall


  • Registered Users Posts: 1,445 ✭✭✭Anjobe


    14ned wrote: »
    time_from_digits() could be compressed into less than six lines, but it's easier to read this way:
    #include <time.h>
    #include <limits.h>
    #include <stdio.h>
    
    int digit(const char *i, int limit)
    {
        int ret=(i[0]-'0')*10+(i[1]-'0');
        return (ret>=limit) ? -1 : ret;
    }
    
    const char *time_from_digits(const char *input)
    {
        struct tm t{digit(input+4, 60), digit(input+2, 60), digit(input+0, 24), 1, 1, 1970, 0, 0, 0, 0, 0};
        if(t.tm_sec<0 || t.tm_min<0 || t.tm_hour<0 || mktime(&t)<0) return "null";
        char *r=asctime(&t)+11;
        r[8]=0;
        return r;
    }
    
    int main(void)
    {
        printf("%s\n", time_from_digits("122304"));
        printf("%s\n", time_from_digits("000000"));
        printf("%s\n", time_from_digits("235960"));
        printf("%s\n", time_from_digits("240100"));
        return 0;
    }
    

    Obviously this is a terrible implementation which nobody should use, but the key is to make use of the standard library functions to do the validation and printing of times. The reason we need to clamp the values by hand is because asctime() is too clever, and automagically "repairs" invalid input silently on your behalf. Any language which is not C would not do such a stupid behaviour, so the above would be much shorter and simpler on say Python, or even C++.

    You can see the above running correctly at https://wandbox.org/permlink/5p4EqctOdfFx8YAh

    Niall

    I think you have missed the point that you may need to rearrange the digits in the input in order to make a valid time, or the earliest time. Your program returns null for the basic test case 000789, and the earliest time that can be made from the digits 122304 is 01:22:34.


  • Advertisement
  • Registered Users Posts: 768 ✭✭✭14ned


    Anjobe wrote: »
    I think you have missed the point that you may need to rearrange the digits in the input in order to make a valid time, or the earliest time. Your program returns null for the basic test case 000789, and the earliest time that can be made from the digits 122304 is 01:22:34.

    I did miss that yes thanks. That makes the problem a bit harder indeed. Would not the combinations be factorial of six? If so, brute forcing it seems easiest. So loop my code above, sort the array of valid outputs, emit the lexographic lowest.

    Definitely more than six lines now though!

    Niall


  • Registered Users Posts: 1 rw999


    def time_from_digets(digits):
        digits.sort()
    
        if digits[0] > 2:
            return None
    
        elif digits[0] == 2:
            if digits[4] > 5:
                digits[3], digits[4] = digits[4], digits[3]
    
            if digits[1] > 3 or digits[2] > 5 or digits[4] > 5:
                return None
            return digits
        else:
            if digits[2] > 5:
                digits[1], digits[2] = digits[2], digits[1]
            if digits[4] > 5:
                if digits[3] < 6:
                    digits[3], digits[4] = digits[4], digits[3]
                else:
                    digits[1], digits[4] = digits[4], digits[1]
                    digits[1], digits[3] = digits[3], digits[1]
            if digits[2] > 5 or digits[4] > 5:
                return None
            return digits
    
    print time_from_digets([0,0,0,7,8,9])
    print time_from_digets([0,0,0,7,8,9]) == [0, 7, 0, 8, 0, 9] 
    print time_from_digets([2,4,5,9,5,9])
    print time_from_digets([2,4,5,9,5,9]) == None
    print time_from_digets([1,2,2,6,0,4])
    print time_from_digets([1,2,2,6,0,4]) == [0, 1, 2, 2, 4, 6]
    print time_from_digets([1,2,2,6,6,6])
    print time_from_digets([1,2,2,6,6,6]) == [1, 6, 2, 6, 2, 6]
    

    I think its a reasonable question to be asked for a grad interview, but I wouldn't be too disappointed that it didn't go well, particularly if this is the first time you've done such an interview. These are some of the things I focus on for interview problems if it helps:

    Read the question carefully and identify useful information. "Earliest time" means you probably want digits in ascending order, and then account for the special cases implied by 24 hour clock, always bearing in mind you want the lowest digits first where possible. I think this question becomes much easier once the first thing your code does is sort the digits.

    TDD is great for these. Try to think of the edge cases, and add a test. The test can be simple, just print to stdout and validate it in your head, particularly if pressed for time. When you write a little code, run the solution to see if it has worked as you intended.

    Get something working. Think about how it could be done in O(n) time/memory or be adapted to handle variations of the question, but get a naive solution working before worrying too much about these things. I often find you see obvious ways for improvement from working out the naive case and you will at least have something to show. This is particularly relevant when applying for a grad role as the interviewer does not necessarily expect the ideal solution.

    Don't worry about style/ugly code. I don't think anyone really places any importance on it for interview style questions.

    Practice helps, and they can be fun to do, as is demonstrated by all the people replying to this thread. I like the website programmingpraxis.com personally.

    Nothing you can do about it, but I prefer when the interviewer is with you for these sort of questions, a good interviewer might have been able to give you a hint when you were struggling and see if you could get further with that, a candidate failing early in the interview is good for no one and it may have just been caused by the stress of the interview.


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    14ned wrote: »
    time_from_digits() could be compressed into less than six lines, but it's easier to read this way:
    #include <time.h>
    #include <limits.h>
    #include <stdio.h>
    
    int digit(const char *i, int limit)
    {
        int ret=(i[0]-'0')*10+(i[1]-'0');
        return (ret>=limit) ? -1 : ret;
    }
    
    const char *time_from_digits(const char *input)
    {
        struct tm t{digit(input+4, 60), digit(input+2, 60), digit(input+0, 24), 1, 1, 1970, 0, 0, 0, 0, 0};
        if(t.tm_sec<0 || t.tm_min<0 || t.tm_hour<0 || mktime(&t)<0) return "null";
        char *r=asctime(&t)+11;
        r[8]=0;
        return r;
    }
    
    int main(void)
    {
        printf("%s\n", time_from_digits("122304"));
        printf("%s\n", time_from_digits("000000"));
        printf("%s\n", time_from_digits("235960"));
        printf("%s\n", time_from_digits("240100"));
        return 0;
    }
    

    Obviously this is a terrible implementation which nobody should use, but the key is to make use of the standard library functions to do the validation and printing of times. The reason we need to clamp the values by hand is because asctime() is too clever, and automagically "repairs" invalid input silently on your behalf. Any language which is not C would not do such a stupid behaviour, so the above would be much shorter and simpler on say Python, or even C++.

    You can see the above running correctly at https://wandbox.org/permlink/5p4EqctOdfFx8YAh

    Niall

    Making and returning an in-situ modification of the buffer returned by asctime makes baby Jesus cry. I think your synopsis that this problem benefits from use of the standard library and then having a go at C because you don't like the standard library is way off base here. A simpler standalone implementation for the functionality is as follows
    int format_and_validate_time(char *input, char *output)
    {
       int h,m,s;
    
       h = (input[0]-'0')*10 + (input[1]-'0'); 
       m = (input[2]-'0')*10 + (input[3]-'0');
       s = (input[4]-'0')*10 + (input[5]-'0');
       if ((h >= 24) || (h < 0)  || (m >= 60) || (m < 0)  || (s >= 60) || (s < 0))
         return -1;
       output[0] = input[0]; output[1] = input[1]; output[2] = ':';
       output[3] = input[2]; output[4] = input[3]; output[5] = ':';
       output[6] = input[4]; output[7] = input[5];
       return 0;
    }
    

    If I'm honest, the reason I raised the six lines of C thing is that the OP came on here as a relatively inexperienced programmer looking for reassurances that a problem is non-trivial and you tell them the opposite. Poor form IMHO.


  • Registered Users Posts: 6,016 ✭✭✭Talisman


    If you think about the properties of a valid HH:MM:SS formatted string you can simplify the task and return null early in the cases where it is easy to tell the string will not be valid.

    HH - must be less than 24 -> if the list of numbers is a sorted array then the first element must be less than 3 and the second element must be less than 4 if the first is 2. Here is a simple check:
    if (sorted[0] * 10 + sorted[1] > 23)
      return null
    

    If you split the elements of the array into two collections low_numbers (0..5) and high_numbers (6..9) you can determine if it's possible to create a valid string. If the size of the low_numbers collection is smaller than high_numbers then it's not possible.
    check = low_numbers.length - high_numbers.length
    if (check < 0)
      return null
    

    Once those checks are passed building the string is trivial but you should perform checks to ensure that HH is less than 24, and that both MM and SS are less than 60.


  • Registered Users Posts: 1,298 ✭✭✭off.the.walls


    If you're going for interviews OP https://www.codewars.com get on there and do a few of em, will help you get into the mindset for a bit of it.


  • Registered Users Posts: 768 ✭✭✭14ned


    smacl wrote: »
    If I'm honest, the reason I raised the six lines of C thing is that the OP came on here as a relatively inexperienced programmer looking for reassurances that a problem is non-trivial and you tell them the opposite. Poor form IMHO.

    That's fair. I misread the original question. I agree it's no longer trivial if read correctly, but it's also not especially hard. I've certainly seen far harder questions in interviews e.g. "Given this city map, estimate the optimal number and location of fire engine stations such that a fire engine can reach any point in the city within ten minutes".

    I'm told it's actually quite easy, but it defeated me on the day. That was a Google interview question, incidentally.

    Niall


  • Posts: 17,381 [Deleted User]


    Talisman wrote: »
    If you think about the properties of a valid HH:MM:SS formatted string you can simplify the task and return null early in the cases where it is easy to tell the string will not be valid.

    HH - must be less than 24 -> if the list of numbers is a sorted array then the first element must be less than 3 and the second element must be less than 4 if the first is 2. Here is a simple check:
    if (sorted[0] * 10 + sorted[1] > 23)
      return null
    

    If you split the elements of the array into two collections low_numbers (0..5) and high_numbers (6..9) you can determine if it's possible to create a valid string. If the size of the low_numbers collection is smaller than high_numbers then it's not possible.
    check = low_numbers.length - high_numbers.length
    if (check < 0)
      return null
    

    Once those checks are passed building the string is trivial but you should perform checks to ensure that HH is less than 24, and that both MM and SS are less than 60.

    You've skipped a lot of the complications. You can't just sort the array.

    Am I the only one who has actually finished this? I was expecting more solutions.


  • Registered Users Posts: 6,016 ✭✭✭Talisman


    You've skipped a lot of the complications. You can't just sort the array.

    Am I the only one who has actually finished this? I was expecting more solutions.
    My intention wasn't to provide a complete solution - by determining the elements won't make a valid string you can provide the null solution early.

    If I were the interviewer that is the nugget that I would be looking for the candidate to show in their solution - if they don't provide a complete solution, you can tease it out of them during the process but they should know that it's best to get to the fail case as early as possible and not waste valuable CPU cycles.


  • Moderators, Society & Culture Moderators Posts: 15,718 Mod ✭✭✭✭smacl


    14ned wrote: »
    I've certainly seen far harder questions in interviews e.g. "Given this city map, estimate the optimal number and location of fire engine stations such that a fire engine can reach any point in the city within ten minutes".

    I'm told it's actually quite easy, but it defeated me on the day. That was a Google interview question, incidentally.

    Person who told you that was easy might need to define easy. At first glance it looks like something you could solve using weighted directed graphs, with streets as edges and junctions as vertices. Weighted, as the length taken to traverse a given street will vary by its length and other possible traffic restrictions (e.g. number of lanes). Directed, as some streets are one-way. This however isn't the case, as different junctions take different times to traverse depending on where you're entering and exiting and the type of junction. You also have multiple possible fire station locations and fire incident locations on any given street, so you have junctions as one type of vertex and building positions as another. Given this as the starting position you can write a cost function that computes the most efficient route between any two locations in terms of minutes. For any given location you can then compile a list of all locations within a 10 minute radius, consider this as a potential fire station location, and flag all these locations used. Having done this you can then select any unflagged location, repeat the process and add all unflagged locations in its 10 minute radius. Repeat this until all locations are flagged to get a single potential solution and count the number of fire stations. Repeat for all possible solutions and pick the one with the minimum number of fire stations. This is a naive brute force solution with a high order of complexity that is going to fall down on any reasonably sized real world data. Even at that, I wouldn't consider it that easy to code. Nor is it something that is likely to play well with a generic graph theory library.


  • Advertisement
  • Closed Accounts Posts: 22,651 ✭✭✭✭beauf


    Could you not average journey times, and create a circle that defines this range from station for each station.
    Then work out how many circles are need to overlay the area of the city map. Could be square either.


Advertisement