Finding Nearest Stores for each Houses
Last Updated :
13 Feb, 2024
Given two arrays representing integer locations of stores[] and houses[] (each location in this problem is one-dimensional). The task is to find an integer array result[], where result[i] should denote the location of the store closest to the i-th house. If many stores are equidistant from a particular house, choose the store with the smallest numerical location.
Note: There may be multiple stores and houses at the same location.
Examples:
Input: houses = [5, 10, 17], stores = [1, 5, 20, 11, 16]
Output: [5, 11, 16]
Explanation: The closest store to the house at location 5 is the store at the same location.
The closest store to the house at location 10 is the store at the location 11.
The closest store to the house at location 17 is the store at the location 16.
Input: houses = [2, 4, 2], stores = [5, 1, 2, 3]
Output: [2, 3, 2]
Input: houses = [4, 8, 1, 1], stores = [5, 3, 1, 2, 6]
Output: [3, 6, 1, 1]
Finding Nearest Stores for each Houses using Binary Search:
The idea behind use binary search for search the closest stores for each houses. First sort the order of store locations. By performing binary search, we can quickly locate the nearest store to each house, optimizing the search process. This approach minimizes the time complexity and efficiently finds the closest store for each house, making it a great choice when dealing with a large number of houses and stores.
Step-by-step approach:
- For each house, uses the lower_bound() function to find the store location that is greater than or equal to the current house location.
- If the located store matches the house’s location, added this location to the result.
- If the located store is different from the house’s location,
- Calculates the distances to the left and right stores then selects the closer store as the nearest one and adds it to the result.
- If there is no store to the left, adds the closest store to the right to the result.
- Finally, returns the result array.
Below is the implementation of the above approch.
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > closestStore(vector< int >& houses,
vector< int >& stores)
{
sort(stores.begin(), stores.end());
vector< int > result;
for ( int i = 0; i < houses.size(); i++) {
auto l = lower_bound(stores.begin(), stores.end(),
houses[i]);
if (l != stores.end()) {
if (*l == houses[i]) {
result.push_back(*l);
}
else {
auto r = l;
if (--l != stores.begin()) {
int closestStoreToLeft
= abs (houses[i] - *l);
int closestStoreToRight
= abs (houses[i] - *r);
if (closestStoreToLeft
<= closestStoreToRight) {
result.push_back(*l);
}
else {
result.push_back(*r);
}
}
else {
result.push_back(*l);
}
}
}
else {
result.push_back(*(--l));
}
}
return result;
}
int main()
{
vector< int > houses = { 4, 8, 1, 1 };
vector< int > stores = { 5, 3, 1, 2, 6 };
vector< int > result = closestStore(houses, stores);
for ( auto i : result) {
cout << i << " " ;
}
return 0;
}
|
Java
import java.util.*;
public class ClosestStore {
public static List<Integer> closestStore(List<Integer> houses, List<Integer> stores) {
Collections.sort(stores);
List<Integer> result = new ArrayList<>();
for ( int house : houses) {
int idx = Collections.binarySearch(stores, house);
if (idx >= 0 ) {
result.add(stores.get(idx));
} else {
idx = -idx - 1 ;
if (idx > 0 && idx < stores.size()) {
int closestStoreToLeft = Math.abs(house - stores.get(idx - 1 ));
int closestStoreToRight = Math.abs(house - stores.get(idx));
if (closestStoreToLeft <= closestStoreToRight) {
result.add(stores.get(idx - 1 ));
} else {
result.add(stores.get(idx));
}
} else if (idx == 0 ) {
result.add(stores.get(idx));
} else {
result.add(stores.get(idx - 1 ));
}
}
}
return result;
}
public static void main(String[] args) {
List<Integer> houses = Arrays.asList( 4 , 8 , 1 , 1 );
List<Integer> stores = Arrays.asList( 5 , 3 , 1 , 2 , 6 );
List<Integer> result = closestStore(houses, stores);
for ( int i : result) {
System.out.print(i + " " );
}
}
}
|
Python3
def closest_store(houses, stores):
stores.sort()
result = []
for house in houses:
index = bisect.bisect_left(stores, house)
if index ! = len (stores):
if stores[index] = = house:
result.append(stores[index])
else :
if index > 0 :
closest_store_to_left = abs (house - stores[index - 1 ])
closest_store_to_right = abs (house - stores[index])
if closest_store_to_left < = closest_store_to_right:
result.append(stores[index - 1 ])
else :
result.append(stores[index])
else :
result.append(stores[index])
else :
result.append(stores[index - 1 ])
return result
if __name__ = = "__main__" :
import bisect
houses = [ 4 , 8 , 1 , 1 ]
stores = [ 5 , 3 , 1 , 2 , 6 ]
result = closest_store(houses, stores)
for i in result:
print (i, end = " " )
|
C#
using System;
using System.Collections.Generic;
class Program
{
static List< int > ClosestStore(List< int > houses, List< int > stores)
{
stores.Sort();
List< int > result = new List< int >();
foreach ( int house in houses)
{
int index = stores.BinarySearch(house);
if (index >= 0)
{
result.Add(stores[index]);
}
else
{
int rightIndex = ~index;
int leftIndex = rightIndex - 1;
int closestStoreToLeft = leftIndex >= 0 ? house - stores[leftIndex] : int .MaxValue;
int closestStoreToRight = rightIndex < stores.Count ? stores[rightIndex] - house : int .MaxValue;
if (closestStoreToLeft <= closestStoreToRight)
{
result.Add(stores[leftIndex]);
}
else
{
result.Add(stores[rightIndex]);
}
}
}
return result;
}
static void Main( string [] args)
{
List< int > houses = new List< int > { 4, 8, 1, 1 };
List< int > stores = new List< int > { 5, 3, 1, 2, 6 };
List< int > result = ClosestStore(houses, stores);
foreach ( int store in result)
{
Console.Write(store + " " );
}
}
}
|
Javascript
function closestStore(houses, stores) {
stores.sort((a, b) => a - b);
let result = [];
for (let i = 0; i < houses.length; i++) {
let l = stores.findIndex(store => store >= houses[i]);
if (l !== -1) {
if (stores[l] === houses[i]) {
result.push(stores[l]);
} else {
let r = l;
if (l - 1 >= 0) {
let closestStoreToLeft = Math.abs(houses[i] - stores[l - 1]);
let closestStoreToRight = Math.abs(houses[i] - stores[r]);
if (closestStoreToLeft <= closestStoreToRight) {
result.push(stores[l - 1]);
} else {
result.push(stores[r]);
}
} else {
result.push(stores[r]);
}
}
} else {
result.push(stores[stores.length - 1]);
}
}
return result;
}
function main() {
let houses = [4, 8, 1, 1];
let stores = [5, 3, 1, 2, 6];
let result = closestStore(houses, stores);
console.log(result.join( " " ));
}
main();
|
Time Complexity: O(M*log(M) + N*log(M)), where N and M are the length of houses and stores respectively.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...