Compare Two Numbers with Relational Operators

Solve this Problem
Easy10 min
Topics
Companies
Given two integers a and b, evaluate the six relational operatorsRelational OperatorsOperators that compare two values and produce true or false: ==, !=, <, <=, >, >=. on them in the order ==, !=, <, <=, >, >=, and return 1 for each true comparison and 0 for each false one. Every if and every loop condition is built from these comparisons. The second solution shows that they are not independent: once you know whether a equals b and whether a is less than b, the other four follow by combining or negatingNegationFlipping a boolean: true becomes false and false becomes true (the ! operator, or not in Python). those two.

Test Case 1:

Input:a = 4, b = 9
Output:[0,1,1,1,0,0]
Explanation:Order: ==, !=, <, <=, >, >=. 4 is smaller, so the "not equal", "less" and "less or equal" checks are true.

Test Case 2:

Input:a = 6, b = 6
Output:[1,0,0,1,0,1]
Explanation:Equal values satisfy ==, <= and >=, but not the strict < and >.

Constraints

  • ◆-1000000 ≤ a, b ≤ 1000000

Try the Dry Run

Approach & Solutions

One Comparison per ResultGood

Apply each of the six relational operators to a and b and store 1 when the comparison is true and 0 when it is false, using the ternary operator. JavaScript uses === and !== for strict equality.

TimeO(1)
SpaceO(1)
class Solution { public int[] relationalResults(int a, int b) { int[] result = new int[6]; result[0] = a == b ? 1 : 0; result[1] = a != b ? 1 : 0; result[2] = a < b ? 1 : 0; result[3] = a <= b ? 1 : 0; result[4] = a > b ? 1 : 0; result[5] = a >= b ? 1 : 0; return result; } }
Derive Everything from Two ComparisonsOptimal

Only two facts are really needed: are a and b equal, and is a less than b? Every other relation follows: != is "not equal", <= is "less or equal", > is "not less-or-equal" and >= is "not less". This shows how the six operators are related to one another.

TimeO(1)
SpaceO(1)
class Solution { public int[] relationalResults(int a, int b) { boolean equal = a == b; boolean less = a < b; boolean lessOrEqual = less || equal; return new int[] { equal ? 1 : 0, equal ? 0 : 1, less ? 1 : 0, lessOrEqual ? 1 : 0, lessOrEqual ? 0 : 1, less ? 0 : 1 }; } }

Related Problems