Distance Travelled in a Permutation of 1 to n

Last Updated : 24 Jul, 2026

Given an array arr[] consisting of a permutation of the set [1, 2, 3, …, n] for some positive integer n. Find the total distance you must travel starting from the position of the number 1 in the array, then moving to the position of the number 2, and so on, until you reach the position of n. When you travel from arr[i] to arr[j], the distance travelled is |i– j|.

Examples:

Input: arr[] = [5, 1, 4, 3, 2]
Output: 7
Explanation: The numbers 1 to 5 are present at indexes 1, 4, 3, 2 and 0 respectively. Total distance = |4 - 1| + |3 - 4| + |2 - 3| + |0 - 2| = 3 + 1 + 1 + 2 = 7.

Input: arr[] = [6, 5, 1, 2, 4, 3]
Output: 8
Explanation: Total distance = |2 - 3| + |3 - 5| + |5 - 4| + |4 - 1| + |1 - 0| = 1 + 2 + 1 + 3 + 1 = 8.

Try It Yourself
redirect icon

[Naive Approach] Linear Search for Every Number - O(n ^ 2) Time and O(1) Space

The idea is to find the position of each number from 1 to n by traversing the entire array. After finding the positions of two consecutive numbers, add the absolute difference of their indices to the answer.

C++
#include <iostream>
#include <vector>
using namespace std;

int distance(vector<int> &arr)
{
    int n = arr.size();

    int dis = 0;

    // Find position of each number from 1 to n
    for (int num = 1; num < n; num++)
    {
        int pos1 = -1, pos2 = -1;

        // Find positions of num and num + 1
        for (int i = 0; i < n; i++)
        {
            if (arr[i] == num)
            {
                pos1 = i;
            }
            if (arr[i] == num + 1)
            {
                pos2 = i;
            }
        }

        // Add distance between consecutive numbers
        dis += abs(pos1 - pos2);
    }

    return dis;
}

int main()
{
    vector<int> arr = {6, 5, 1, 2, 4, 3};

    cout << distance(arr);

    return 0;
}
Java
import java.util.Arrays;

public class GFG {
    public static int distance(int[] arr)
    {
        int n = arr.length;

        int dis = 0;

        // Find position of each number from 1 to n
        for (int num = 1; num < n; num++) {
            int pos1 = -1, pos2 = -1;

            // Find positions of num and num + 1
            for (int i = 0; i < n; i++) {
                if (arr[i] == num) {
                    pos1 = i;
                }
                if (arr[i] == num + 1) {
                    pos2 = i;
                }
            }

            // Add distance between consecutive numbers
            dis += Math.abs(pos1 - pos2);
        }

        return dis;
    }

    public static void main(String[] args)
    {
        int[] arr = { 6, 5, 1, 2, 4, 3 };

        System.out.println(distance(arr));
    }
}
Python
def distance(arr):
    n = len(arr)

    dis = 0

    # Find position of each number from 1 to n
    for num in range(1, n):
        pos1 = -1
        pos2 = -1

        # Find positions of num and num + 1
        for i in range(n):
            if arr[i] == num:
                pos1 = i
            if arr[i] == num + 1:
                pos2 = i

        # Add distance between consecutive numbers
        dis += abs(pos1 - pos2)

    return dis

if __name__ == "__main__":
    arr = [6, 5, 1, 2, 4, 3]

    print(distance(arr))
C#
using System;

public class GFG {
    public static int distance(int[] arr)
    {
        int n = arr.Length;

        int dis = 0;

        // Find position of each number from 1 to n
        for (int num = 1; num < n; num++) {
            int pos1 = -1, pos2 = -1;

            // Find positions of num and num + 1
            for (int i = 0; i < n; i++) {
                if (arr[i] == num) {
                    pos1 = i;
                }
                if (arr[i] == num + 1) {
                    pos2 = i;
                }
            }

            // Add distance between consecutive numbers
            dis += Math.Abs(pos1 - pos2);
        }

        return dis;
    }

    public static void Main()
    {
        int[] arr = { 6, 5, 1, 2, 4, 3 };

        Console.WriteLine(distance(arr));
    }
}
JavaScript
function distance(arr) {
    const n = arr.length;

    let dis = 0;

    // Find position of each number from 1 to n
    for (let num = 1; num < n; num++) {
        let pos1 = -1, pos2 = -1;

        // Find positions of num and num + 1
        for (let i = 0; i < n; i++) {
            if (arr[i] === num) {
                pos1 = i;
            }
            if (arr[i] === num + 1) {
                pos2 = i;
            }
        }

        // Add distance between consecutive numbers
        dis += Math.abs(pos1 - pos2);
    }

    return dis;
}

// Driver Code
const arr = [6, 5, 1, 2, 4, 3];

console.log(distance(arr));

Output
8

[Expected Approach] Store Position of Every Element - O(n) Time and O(n) Space

The idea is to store the index of every element in a position array. Since the array is a permutation of 1 to n, positions[i] stores the index of element i + 1 in the original array. Then, compute the sum of absolute differences between the positions of consecutive elements from 1 to n.

Let us understand with example:
Input: arr[] = [6, 5, 1, 2, 4, 3]

  • Create a position array and store the index of each element: positions = [2, 3, 5, 4, 1, 0]
  • Here, positions[0] = 2 means 1 is present at index 2, positions[1] = 3 means 2 is present at index 3, and so on.
  • Calculate distances between consecutive numbers: |2-3| + |3-5| + |5-4| + |4-1| + |1-0|.
  • This gives 1 + 2 + 1 + 3 + 1 = 8.
  • Therefore, the total distance travelled is 8.
C++
#include <iostream>
#include <vector>
using namespace std;

long long distance(vector<int> &arr)
{
    int n = arr.size();

    // Vector to store the positions of each 
    // element in the original array
    vector<int> positions(n);

    // Storing the position of each element
    // in the vector 'positions'
    for (int i = 0; i < n; i++)
    {
        positions[arr[i] - 1] = i;
    }

    // Calculating the total distance between 
    // consecutive elements in their correct positions
    long long dis = 0;
    for (int i = 0; i < n - 1; i++)
    {
        dis += abs(positions[i] - positions[i + 1]);
    }

    return dis;
}

int main()
{
    vector<int> arr = {6, 5, 1, 2, 4, 3};

    cout << distance(arr);

    return 0;
}
Java
import java.util.Arrays;

public class GFG {
    public static long distance(int[] arr)
    {
        int n = arr.length;

        // Array to store the positions of each element in
        // the original array
        int[] positions = new int[n];

        // Storing the position of each element in the array
        // 'positions'
        for (int i = 0; i < n; i++) {
            positions[arr[i] - 1] = i;
        }

        // Calculating the total distance between
        // consecutive elements in their correct positions
        long dis = 0;
        for (int i = 0; i < n - 1; i++) {
            dis += Math.abs(positions[i]
                            - positions[i + 1]);
        }

        return dis;
    }

    public static void main(String[] args)
    {
        int[] arr = { 6, 5, 1, 2, 4, 3 };

        System.out.println(distance(arr));
    }
}
Python
def distance(arr):
    n = len(arr)

    # List to store the positions of each 
    # element in the original array
    positions = [0] * n

    # Storing the position of each element
    # in the list 'positions'
    for i in range(n):
        positions[arr[i] - 1] = i

    # Calculating the total distance between
    # consecutive elements in their correct positions
    dis = 0
    for i in range(n - 1):
        dis += abs(positions[i] - positions[i + 1])

    return dis

if __name__ == "__main__":
    arr = [6, 5, 1, 2, 4, 3]

    print(distance(arr))
C#
using System;

public class GFG {
    public static long distance(int[] arr)
    {
        int n = arr.Length;

        // Array to store the positions of each element in
        // the original array
        int[] positions = new int[n];

        // Storing the position of each element in the array
        // 'positions'
        for (int i = 0; i < n; i++) {
            positions[arr[i] - 1] = i;
        }

        // Calculating the total distance between
        // consecutive elements in their correct positions
        long dis = 0;
        for (int i = 0; i < n - 1; i++) {
            dis += Math.Abs(positions[i]
                            - positions[i + 1]);
        }

        return dis;
    }

    public static void Main()
    {
        int[] arr = { 6, 5, 1, 2, 4, 3 };

        Console.WriteLine(distance(arr));
    }
}
JavaScript
function distance(arr) {
    const n = arr.length;

    // Array to store the positions of each
    // element in the original array
    const positions = new Array(n).fill(0);

    // Storing the position of each
    // element in the array 'positions'
    for (let i = 0; i < n; i++) {
        positions[arr[i] - 1] = i;
    }

    // Calculating the total distance between
    // consecutive elements in their correct positions
    let dis = 0;
    for (let i = 0; i < n - 1; i++) {
        dis += Math.abs(positions[i] - positions[i + 1]);
    }

    return dis;
}

// Driver Code
const arr = [6, 5, 1, 2, 4, 3];

console.log(distance(arr));

Output
8
Comment