703389. Total distance travelled in an array

Easy

Total Distance Travelled in an Array

Summary

Given an array of integers, find the total distance travelled by an element. The distance is calculated as the absolute difference between consecutive elements. This problem involves basic algorithmic concepts like array manipulation and mathematical operations.

Detailed Explanation

The problem can be solved using a simple iteration through the array. For each pair of adjacent elements, calculate the absolute difference (distance) and add it to the total distance travelled.

Here's a step-by-step breakdown:

  1. Initialize a variable total_distance to 0.
  2. Iterate through the array from index 1 to the second last element (since we're comparing adjacent elements).
  3. For each pair of adjacent elements, calculate the absolute difference (distance) as abs(arr[i] - arr[i-1]).
  4. Add the calculated distance to the total distance travelled: total_distance += distance.
  5. Return the final total distance travelled.

Time complexity analysis: The algorithm iterates through the array once, so the time complexity is O(n), where n is the size of the input array.

Space complexity analysis: The algorithm requires a single variable to store the total distance travelled, so the space complexity is O(1).

Optimized Solutions

Java

View on GeeksforGeeks
public int totalDistance(int[] arr) {
    int total_distance = 0;
    for (int i = 1; i < arr.length - 1; i++) {
        int distance = Math.abs(arr[i] - arr[i-1]);
        total_distance += distance;
    }
    return total_distance;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.