Swap Two Array Elements
Updated
Problem statement
Given an integer array nums and two valid zero-based indices i and j, exchange the values at those positions and return the resulting array. Every other position must retain its original value.
For this exercise, assume the two indices may be equal. In that case, the array is unchanged. Modifying the input array is allowed.
Function
swapElements(nums: int[], i: int, j: int) → int[]Examples
Example 1
nums = [4,8,1,9]i = 1j = 3return = [4,9,1,8]Only positions 1 and 3 exchange values: 8 and 9.
Example 2
nums = [6,2]i = 0j = 0return = [6,2]Both indices identify the same position, so no value changes.
Constraints
- For this exercise, assume
1 <= nums.length <= 10^5. -10^9 <= nums[k] <= 10^9.0 <= i, j < nums.length.
More PeopleStrong interview questions
- Reverse Linked-List Nodes in Groups of KOA · PHONE SCREEN · Seen Mar 2026
- Unique Paths Through a GridOA · Seen Mar 2026
- Aggressive CowsOA · Seen Oct 2021
- Shortest Path in an Unweighted GraphOA · Seen Oct 2021
- Total Set Bits from 1 to NOA · Seen Oct 2021
- Minimum Travel Time with Flashing Traffic LightsOA · Seen Aug 2021
- Permutation in a StringOA · Seen Aug 2021
- Rat in a Maze: All Simple PathsOA · Seen Aug 2021
- Add Two Binary StringsONSITE INTERVIEW · Seen Mar 2026
- Four SumONSITE INTERVIEW · Seen Mar 2026
Similar questions at other companies
- Count User Mentions in Chat MessagesRamp · OARamp interview questions
- Count Valid Square PairsAuxoAI · OA
- Catch Fish with Reusable BaitsSusquehanna International Group (SIG) · OASusquehanna International Group (SIG) interview questions
- Two SumAmazon · OA · PHONE SCREEN
- Count Strictly Increasing Contiguous WindowsIBM · OAIBM interview questions
- Find Words That Can Be Formed by CharactersTabaPay · OA
- Server InvestmentRippling · OARippling interview questions
- Book Reading EveningsGoogle · OAGoogle interview questions
- Minimum Index Distance Between Person and CakeSnowflake · OA · PHONE SCREENSnowflake interview questions
- Basic Item DiscountsPalantir · OAPalantir interview questions