703047. Facing the sun

Easy

Facing the Sun

Slug: facing-the-sun2126 Difficulty: Easy Id: 703047 Topic Tags: Arrays, Searching, Data Structures, Algorithms Company Tags: Amazon

Summary

The problem "Facing the Sun" is about finding the minimum number of turns required to face the sun from a given direction. The input is an array representing the directions (0 for north, 1 for south, 2 for east, and 3 for west) in which the sun was facing at each minute during the day. The algorithm should return the minimum number of turns required to face the sun.

Detailed Explanation

The problem can be solved by iterating through the array and calculating the absolute difference between the current direction and the next one. This difference represents the number of turns required to face the sun in that direction. Since the sun always moves in a consistent direction, we only need to consider the minimum number of turns required to reach the first turn where the sun is facing east.

Here's a step-by-step breakdown:

  1. Initialize a variable turns to 0.
  2. Iterate through the array starting from the second element (index 1).
  3. For each direction, calculate the absolute difference between the current direction and the next one.
  4. If the difference is greater than or equal to 2, it means we need to turn back to face the sun, so increment turns by the difference - 2.
  5. Continue iterating until the end of the array.

Time complexity: O(n), where n is the size of the input array. Space complexity: O(1), as we only use a constant amount of space to store the turns variable.

Optimized Solutions

Java

View on GeeksforGeeks
public int facingTheSun(int[] directions) {
    int turns = 0;
    for (int i = 1; i < directions.length; i++) {
        int diff = Math.abs(directions[i] - directions[i-1]);
        if (diff >= 2) {
            turns += diff - 2;
        }
    }
    return turns;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.