Page 1 of 1

Find single number

Posted: Tue Aug 11, 2020 8:52 am
by cameyo
Given a list of positive integers each number appears twice except one number. Find the single number.
Note: The function has to traverse the list only once (O(n)).

Re: Find single number

Posted: Wed Aug 12, 2020 6:44 am
by fdb
HI Cameyo,

I would do something like this, using a hash table:

Code: Select all

(define (find-number lst)
	(define Myhash:Myhash)  ; hash table creation, O(1) lookup time
	(set ' total 0)
	(dolist (n lst)
	(if (Myhash n)
		(dec total n)    ; decrease when already added before
		(begin 
			(Myhash n true)
			(inc total n))))  ; if not in hash table increase
	(delete 'Myhash)  ; first to delete contents and namespace
	(delete 'Myhash)  ; second to delete symbol
	total)

(find-number '(1 2 3 4 5 3 2 1 5))

-> 4

Re: Find single number

Posted: Wed Aug 12, 2020 8:17 am
by cameyo
Hi fdb,
thanks for your solution (hash table is nice).
There is a faster method using a boolean operator...
I'll post my solution in the next days.

cameyo

Re: Find single number

Posted: Thu Aug 13, 2020 11:20 am
by cameyo
My solution using XOR:

Code: Select all

(define (find-number lst) (apply ^ lst))
(find-number '(1 3 1 2 3 4 5 2 4))
;-> 5

Re: Find single number

Posted: Thu Aug 13, 2020 7:45 pm
by fdb
Very nice! An instruction I've never used in practice.