Skip to content
Algorithms for Beginners

Problems / Two pointers

Flip in place

easy

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

Reverse the list items in place: change the list itself so its items are in the opposite order, then return it.

In place means without making a second list. Only use a few extra variables, however long the list is.

Examples

  1. Example 1

    Input
    items = [1, 2, 3, 4, 5]
    Output
    [5, 4, 3, 2, 1]

    With an odd number of items, the middle one stays where it is.

  2. Example 2

    Input
    items = ["h", "e", "y"]
    Output
    ["y", "e", "h"]
  3. Example 3

    Input
    items = []
    Output
    []

    Nothing to flip.

Rules

  • items has between 0 and 100,000 items, of any kind.
  • Don't use the built-in reverse(): the point is to see how it works.
Words on this page, in plain English (3)Open if any word is new to you
Variable
A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
Array (list)
A list of values kept in order, inside square brackets. Like a row of numbered lockers.
In place
Changing the list you were given, instead of making a new one. Saves memory.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function flipInPlace(items) {
  // Reverse items itself, then return it.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in two pointers

  • Learn the two pointers pattern

    Walk through a list from both ends (or at two speeds) at once.

  • Pair in a sorted list

    Easy. Find two prices that add up to a budget, when the prices are already sorted.

  • Squash repeats

    Easy. Remove repeated values from a sorted list in place, keeping one of each.

  • Biggest tank

    Medium. Choose two walls that, with the ground between them, hold the most water.

  • Three to zero

    Medium. Find every different set of three numbers in a list that adds up to zero.

  • Mirror phrase

    Easy. Check whether a phrase reads the same backwards, ignoring spaces, punctuation and capitals.