Lexicographically smallest array
Detailed guide and Python implementation for the 'Lexicographically smallest array' problem.
Problem Statement
Write a function lexicographically_smallest(arr, k) that returns the lexicographically smallest array that can be obtained by swapping adjacent elements at most k times. Elements in arr are unique.
- •1 <= len(arr) <= 1000
- •0 <= k <= 10^5
- •-10^9 <= arr[i] <= 10^9
Examples
lexicographically_smallest([7, 6, 9, 2, 1], 3)
[2, 7, 6, 9, 1]
To get the smallest possible element 2 to the front, we swap 9 and 2, then 6 and 2, then 7 and 2. This takes exactly 3 swaps, resulting in [2, 7, 6, 9, 1].
lexicographically_smallest([2, 1, 3], 1)
[1, 2, 3]
Swap 2 and 1 (1 swap) to get [1, 2, 3].
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.