Closest Value Array Mapping

Introduction

Welcome! Today, we will tackle an engaging problem that will strengthen your Scala programming and problem-solving skills. This task focuses on working with arrays and applying techniques such as sorting and the two-pointer method. By the end of this lesson, you'll have a deeper understanding of how to manipulate arrays efficiently in Scala. Let's get started!

Task Statement

Solution Building: Step 1

Let's begin by constructing a sorted list of pairs from array B. Each pair will contain the value from B and its corresponding index. In Scala, we can achieve this using zipWithIndex to pair each value with its index and then sortBy to sort the pairs by value.

Here's how you can do this in Scala:

Scala
def findAndReplace(A: Array[Int], B: Array[Int]): Array[Int] = {
  val B_sorted = B.zipWithIndex.sortBy(_._1)
  // B_sorted is now an array of (value, index) pairs, sorted by value

You sort by value, so the original order of B is lost in B_sorted. But the original indices are preserved in the second element of the tuple (_._2). This allows you to map back to A correctly.

This sorted array of pairs will help us efficiently search for the closest value to our target in the next steps.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal