Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Check If N and Its Double Exist

Posted on July 25, 2022July 25, 2022 by admin

Overview

An array is given. The objective is to find if there exists any number for which it’s double also exists.

Example 1

Input: [8,5,4,3]
Output: true
Explanation: 4 and 8

Example 2

Input: [1,3,7,9]
Output: false
Explanation: There exists no number for which its double exist

The idea is to use a map here. For every element, we will check  and return true if

  • If its double exists in the map
  • If the number is even then if its half exists in the map

Program

Below is the program for the same

package main

import "fmt"

func checkIfExist(arr []int) bool {
	numMap := make(map[int]bool)

	for i := 0; i < len(arr); i++ {
		if numMap[arr[i]*2] {
			return true
		}
		if arr[i]%2 == 0 && numMap[arr[i]/2] {
			return true
		}
		numMap[arr[i]] = true
	}
	return false
}

func main() {
	output := checkIfExist([]int{8, 5, 4, 3})
	fmt.Println(output)

	output = checkIfExist([]int{1, 3, 7, 9})
	fmt.Println(output)

}

Output:

true
false

Also, check out our system design tutorial series here – System Design Tutorial Series

©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme