Interview Questions/Coding/Diagonal Walker

Diagonal Walker

Preview mode. Log in to edit, run, submit, and save progress.

Easy

Diagonal Walker

You are located on an infinite 2D coordinate plane at position (a, b) and want to reach the destination (c, d). You can perform either of the following moves in one step: Move diagonally up-right: (x, y) → (x + 1, y + 1) Move one unit to the left: (x, y) → (x − 1, y) Determine the minimum number of moves required to reach the destination. If it is not possible to reach (c, d) using the allowed moves, output -1. Input Format: The first line contains an integer t - the number of test cases. Each of the next t lines contains four integers: a b c d where: (a, b) is the starting position. (c, d) is the target position. Output Format: For each test case, print a single integer: The minimum number of moves needed to reach the target position, or -1 if the target cannot be reached.

Examples

Example 1
Input:
1
-1  0  -1  2
Output:
4

Explanation: one possible way using 4 moves is (−1,0)→(0,1)→(−1,1)→(0,2)→(−1,2). It can be proven that it is impossible to move from point (−1,0) to point (−1,2) in less than 4 moves.

Approach hint

Start with the simplest clear approach, explain the trade-off, then move toward the cleaner answer.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

solution.cpp