Ice Cream Parlor

Sort by

recency

|

73 Discussions

|

  • + 0 comments
    def icecreamParlor(m, arr):
        return [[i + 1, len(arr) - arr[::-1].index(m - v)] for i, v in enumerate(arr) if m - v in arr[i+1:]][0]
    
  • + 0 comments

    Java 8 - Used an Index Sort to order the values. One time through the list and to find the correct pair.

        public static List<Integer> icecreamParlor(int m, List<Integer> arr) {
            List<Integer> rtn = new ArrayList<>();
            
            // Index Sort
            int[] indices = IntStream.range(0, arr.size())
                    .boxed()
                    .sorted(Comparator.comparingInt(i -> arr.get(i)))
                    .mapToInt(Integer::intValue)
                    .toArray();
            
            // Close in on the solution
            int l = 0;
            int h = arr.size()-1;
            while(l<h && arr.get(indices[l]) + arr.get(indices[h]) != m) {
                int vh = arr.get(indices[h]);
                int vl = arr.get(indices[l]);
                
                if (vh >= m || (vh + vl) > m)
                    --h;
                else 
                    ++l;           
            }
            
            // sort result into asscending order.
            rtn.add(Math.min( indices[l], indices[h] )+1); 
            rtn.add(Math.max( indices[l], indices[h] )+1); 
            
            return rtn ;
        }
    
  • + 0 comments

    Compact Python solution:

    def icecreamParlor(m, arr):
    
    for i_1,a in enumerate(arr):
    
        for i_2,b in enumerate(arr):
    
            if i_2>i_1:
                if m-arr[i_1]==arr[i_2]:
                    return [i_1+1,i_2+1]
    
  • + 0 comments

    Here is hackerrank ice cream parlor problem solution in Python, Java, C++, C and javascript

  • + 0 comments

    A more elegant O(n) solution, similar to cb_kalz's solution (Scala):

      def icecreamParlor(m: Int, arr: Array[Int]): Array[Int] = {
        arr.zip(1 to Int.MaxValue).foldLeft((None: Option[Array[Int]], Map.empty[Int, Int])) {
          case ((result @ Some(_), acc), _) => (result, acc)
          case ((None, acc), (elem1, i)) =>
            val elem2 = m - elem1
            if (acc.contains(elem2)) (Some(Array(acc(elem2), i).sorted), acc)
            else (None, acc + (elem1 -> i))
        }._1.get
      }