Kotlinlearncs.online LogoJava
Return to List

Solve: Swap Section

Created By: Rohith Sanjay
/ Version: 2024.10.1

Write a method called swapSection that takes in 3 arguments in this order: an IntArray?, a start index (Int), and an end index (also an Int). The problem "swaps" pairs of elements in a section of the array, from the start index (inclusive) to the end index (also inclusive), and returns the swapped/modified array. If you need to swap an odd number of elements, do not change the last element (only swap the pairs before it). Here are some examples:

In the following examples, the swapped elements are in bold.

Example 1 (even length; entire array): Array: [1, 2, 3, 4, 5, 6], startIndex: 0, endIndex: 5. Your method should return the array [2, 1, 4, 3, 6, 5]. Note how each pair is being reversed/swapped (e.g. [1, 2] turns into [2, 1]).

Example 2 (odd length; entire array): Array: [1, 2, 3, 4, 5], startIndex: 0, endIndex: 4. Your method should return [2, 1, 4, 3, 5]. Note how the last element is not being swapped, because it's not part of a pair.

Example 3 (even length; sub-array): Array: [1, 2, 3, 4, 5, 6], startIndex: 1, endIndex: 4. Your method should return the array [1, 3, 2, 5, 4, 6]. In this case, only the sub-array (elements of index 1 through 4) are being swapped. Thus, we swap the pairs only in that sub-array, and keep the rest of the array the same.

Example 4 (odd length; sub-array): Array: [1, 2, 3, 4, 5, 6], startIndex: 1, endIndex: 3. Your method should return the array [1, 3, 2, 4, 5, 6]. Here, we are interested in indices 1, 2, and 3 (3 elements, an odd number), so we do NOT change the last of the 3 elements (only the first pair).

Special Cases:

  1. The passed array can be null! In this case, just return the original array (which is null) with no changes.
  2. The start and end index can be invalid! Specifically, if the start index is higher than the end index, if the start/end indices are larger than the array's length, or if they are negative, then you should just return the original array with no changes.

Hints:

  1. Declare a new array of the same size as the original array's length. Populate (fill up) this array one element at a time, and then return this array at the end.
  2. When you're populating the array to be returned, you may have to set both element i and element i+1, because you're swapping one pair at a time.
  3. Remember: the start and end indices are inclusive for your search bounds!

Related Lessons

Stuck? You may find these lessons helpful:

Report a Problem

Attribution must link to this page: https://www.learncs.online/solve/kotlin/swap-section/[email protected]