HackerRank Service Lane Problem Solution Yashwant Parihar, April 18, 2023April 19, 2023 In this post, we will solve HackerRank Service Lane Problem Solution. A driver is driving on the freeway. The check engine light of his vehicle is on, and the driver wants to get service immediately. Luckily, a service lane runs parallel to the highway. It varies in width along its length. You will be given an array of widths at points along the road (indices), then a list of the indices of entry and exit points. Considering each entry and exit point pair, calculate the maximum size vehicle that can travel that segment of the service lane safely. Examplen = 4width= [2, 3, 2, 1]cases = [[1, 2], [2,4]]If the entry index,i = 1 and the exit, j = 2, there are two segment widths of 2 and 3 respectively. The widest vehicle that can fit through both is 2. If i = 2 and j = 4, the widthsare [3, 2, 1] which limits vehicle width to 1. Function Description Complete the serviceLane function in the editor below. serviceLane has the following parameter(s): int n: the size of the array int cases[t][2]: each element contains the starting and ending indices for a segment to consider, inclusive Returns int[t]: the maximum width vehicle that can pass through each segment of the service lane described Input FormatThe first line of input contains two integers, n and t, where n denotes the number of width measurements and t, the number of test cases. The next line has ʼn space-separated integers which represent the array width.The next t lines contain two integers, & and j, where i is the start index and j is the end index of the segment to check. Sample Input STDIN Function ----- -------- 8 5 n = 8, t = 5 2 3 1 2 3 2 3 3 width = [2, 3, 1, 2, 3, 2, 3, 3] 0 3 cases = [[0, 3], [4, 6], [6, 7], [3, 5], [0, 7]] 4 6 6 7 3 5 0 7 Sample Output 1 2 3 2 1 Explanation Below is the representation of the lane: |HIGHWAY|Lane| -> Width 0: | |--| 2 1: | |---| 3 2: | |-| 1 3: | |--| 2 4: | |---| 3 5: | |--| 2 6: | |---| 3 7: | |---| 3 (0,3): From index 0 through 3 we have widths 2, 3, 1 and 2. Nothing wider than 1 can pass all segments. (4, 6): From index 4 through 6 we have widht 3, 2 and 3. Nothing wider than 2 can pass allsegments. (6,7): 3, 33. (3, 5): 2, 3, 22 (0,7): 2, 3, 1, 2, 3, 2, 3, 3 → 1. HackerRank Service Lane Problem Solution Service Lane C Solution /* * serviceLane.c * InterviewStreet * * Created by Kyle Donnelly on 2/16/14. * */ #include <stdio.h> #include <stdlib.h> int main (void) { int roadLength, cases; int *widths; int *changeIndexes; int numChanges; int start, end; int minWidth; scanf("%d %d", &roadLength, &cases); widths = malloc(sizeof(int) * roadLength); changeIndexes = malloc(sizeof(int) * roadLength); for (int i=0; i<roadLength; i++) { scanf("%d", &widths[i]); } changeIndexes[0] = 0; numChanges = 1; for (int i=1; i<roadLength; i++) { if (widths[i] != widths[i-1]) { changeIndexes[numChanges] = i; numChanges++; } } for (int i=0; i<cases; i++) { minWidth = 3; scanf("%d %d", &start, &end); for (int j=start; j<=end; j++) { if (widths[j] < minWidth) { minWidth = widths[j]; } } printf("%d\n", minWidth); } return 0; } Service Lane C++ Solution #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n,q; cin>>n>>q; vector<int> v(n); for(int i=0;i<n;i++) cin>>v[i]; for(int i=0;i<q;i++) { int a,b; cin>>a>>b; auto min=min_element(v.begin()+a,v.begin()+b+1); cout<<*min<<endl; } return 0; } Service Lane C Sharp Solution using System; using System.Collections.Generic; using System.Linq; namespace Laconic.HackerRank.Algorithms.Warmup.ServiceLane { public class Program { public static void Main() { var firstLine = ReadAndParseInputLine(); var numberOfTestCases = firstLine[1]; var widths = ReadAndParseInputLine(); for (var i = 0; i < numberOfTestCases; i++) { var values = ReadAndParseInputLine(); var startIndex = values[0]; var endIndex = values[1]; var minValue = FindMinValueInSegment(widths, startIndex, endIndex); Console.WriteLine(minValue); } } private static int FindMinValueInSegment(IEnumerable<int> widths, int startIndex, int endIndex) { return widths.Skip(startIndex).Take(endIndex - startIndex + 1).Aggregate(int.MaxValue, Math.Min); } private static int[] ReadAndParseInputLine() { return Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); } } } Service Lane Java Solution import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class Result { /* * Complete the 'serviceLane' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts following parameters: * 1. INTEGER n * 2. 2D_INTEGER_ARRAY cases */ public static List<Integer> serviceLane(int n, List<Integer> width, List<List<Integer>> cases) { List<Integer> result = new ArrayList(); for (List<Integer> interval : cases) { result.add( width.subList( interval.get(0), interval.get(1) + 1 ).stream().min( Comparator.naturalOrder() ).get() ); } return result; } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); int n = Integer.parseInt(firstMultipleInput[0]); int t = Integer.parseInt(firstMultipleInput[1]); List<Integer> width = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList()); List<List<Integer>> cases = new ArrayList<>(); IntStream.range(0, t).forEach(i -> { try { cases.add( Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList()) ); } catch (IOException ex) { throw new RuntimeException(ex); } }); List<Integer> result = Result.serviceLane(n, width, cases); bufferedWriter.write( result.stream() .map(Object::toString) .collect(joining("\n")) + "\n" ); bufferedReader.close(); bufferedWriter.close(); } } Service Lane JavaScript Solution var chunk = ''; var sliceMin = function(arr, start, end) { var slicedArr = arr.slice(start, end); return Math.min.apply(null, slicedArr); } process.stdin.setEncoding('utf8'); process.stdin.on('data', function(data) { chunk += data; }); process.stdin.on('end', function() { var args = chunk.split(/\n/); var N = parseInt(args[0].split(' ')[0], 10); var T = parseInt(args[0].split(' ')[1], 10); var width = []; args[1].split(' ').forEach(function(arg) { arg = parseInt(arg, 10); if (!isNaN(arg)) { width.push(parseInt(arg, 10)); } }); for (var i = 0; i < T; i++) { var start = parseInt(args[i + 2].split(' ')[0], 10); var end = parseInt(args[i + 2].split(' ')[1], 10); process.stdout.write(sliceMin(width, start, end + 1) + '\n'); } }); Service Lane Python Solution #!/usr/bin/python # -*- coding: latin-1 -*- """ HackerRank Challenge Warmup: Service Lane https://www.hackerrank.com/challenges/service-lane ----------------------- Olivier Pirson http://www.opimedia.be/ """ from __future__ import division from __future__ import print_function import sys DEBUG = len(sys.argv) > 1 def calculate(i, j): return min(widths[i:j + 1]) def read_tests(): length, nb_test = [int(n) for n in sys.stdin.readline().split()] widths = tuple([int(n) for n in sys.stdin.readline().split()]) assert len(widths) == length tests = tuple([tuple([int(n) for n in sys.stdin.readline().split()]) for i in range(nb_test)]) assert len(tests) == nb_test if DEBUG: print('length: {}\t# tests: {}\twidths: {}' .format(length, nb_test, widths), file=sys.stderr) sys.stderr.flush() return (length, tests, widths) length, tests, widths = read_tests() for i, j in tests: if DEBUG: print('{}, {}:'.format(i, j), file=sys.stderr) sys.stderr.flush() print(calculate(i, j)) Other Solution HackerRank Lisa’s Workbook Problem Solution HackerRank Flatland Space Stations Solution c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython