26
\$\begingroup\$

Write a program which finds the non-unique elements of an array of signed integers. The resulting array can be in any order.

Your answer may be a snippet which assumes the input to be stored in a variable (d, say) and evaluates to the correct result.

Test Cases

Each test case is a single line in the format input => output. Note that other permutations of the output are valid as well.

[]                        => []
[-1, 0, 1]                => []
[1, 1]                    => [1]
[3, 0, 0, 1, 1, 0, 5, 3]  => [3, 0, 1]
[-34, 0, 1, -34, 4, 8, 4] => [-34, 4]

Order of the elements doesn't matter.

This is code golf, so the shortest answer (in bytes) wins.

\$\endgroup\$
6
  • 5
    \$\begingroup\$ Related \$\endgroup\$
    – Sp3000
    Oct 13, 2015 at 10:11
  • 1
    \$\begingroup\$ since this is for array of integers code would be different. I think much shorter. That is for a string. \$\endgroup\$
    – garg10may
    Oct 13, 2015 at 10:21
  • 2
    \$\begingroup\$ Are we allowed to accept input as lines instead of as an array? For example, instead of [-1, 0, 1], can we input (replace \n with newlines): "-1\n0\n1"? \$\endgroup\$ Oct 13, 2015 at 15:01
  • 1
    \$\begingroup\$ Does the output have to be a list or would a set be acceptable? \$\endgroup\$
    – Dennis
    Oct 13, 2015 at 15:06
  • \$\begingroup\$ And does it have to output in that format? \$\endgroup\$ Oct 13, 2015 at 15:06

60 Answers 60

1
2
2
\$\begingroup\$

Octave, 33 bytes

[~,a]=unique(d);d(a)=[];unique(d)
  • Finds the indices of the first occurrence of each unique integer,
  • removes those occurrences, and
  • finds the unique elements of the remaining array.

Here it is on ideone. I've wrapped the snippet in a function so I could call it using all of the sample inputs.

\$\endgroup\$
2
\$\begingroup\$

Java 8, 80 Bytes

x.stream().filter(i->x.indexOf(i)!=x.lastIndexOf(i)).collect(Collectors.toSet())

Assuming x contains the input List of numbers.

\$\endgroup\$
2
\$\begingroup\$

PHP, 35 37 bytes

Pretty straight forward:

array_diff_key($a,array_unique($a))

As a note: I didn't add the ; at the end of the line, as the questions states:

Your answer may be a snippet which assumes the input to be stored in a variable (d, say) and evaluates to the correct result

So this snippet could be used like this and evaluates to the correct result:

print implode(' ', array_diff_key($a,array_unique($a)));

Another note

The code above works for all test cases provided in the challenge. In those all non-unique characters are at most duplicates. If a element can occur more than two times, another array_unique() would be necessary, which increases the length to 49 bytes:

array_unique(array_diff_key($a,array_unique($a)))

Edits

  • Saved 2 bytes by replacing array_diff_assoc with array_diff_key. Thanks to Jörg Hülsermann.
\$\endgroup\$
2
  • 1
    \$\begingroup\$ array_diff_key instead array_diff_assoc \$\endgroup\$ May 8, 2017 at 17:48
  • \$\begingroup\$ @JörgHülsermann Good catch. Thanks. Will take a look at your other suggestions within the next days. \$\endgroup\$ May 10, 2017 at 14:20
2
\$\begingroup\$

Japt, 7 bytes

â £kX â

Try it online!

Explanation:

â £kX â
â         // Get all unique items from the input
  £       // Map X through the results
   kX     //   Remove X from the input
      â   //   Get unique items
-h        // Return the last item
\$\endgroup\$
2
\$\begingroup\$

Factor, 10 bytes

duplicates

Try it online!

Builtin

\$\endgroup\$
2
\$\begingroup\$

Curry (PAKCS), 58 bytes

x!(y:z)|elem y z&&all(/=y)x=y:(y:x)!z|1>0=x!z
_![]=[]
([]!)

Attempt This Online!

Weirdish port of my Elm answer. Curry has nicer built in functions and pattern matching than Elm.

\$\endgroup\$
2
\$\begingroup\$

Elm, 91 bytes

e=List.member
g x z=case z of
 a::b->g(a::x)b++if e a b&&not(e a x)then[a]else[]
 _->[]
g[]
\$\endgroup\$
1
  • \$\begingroup\$ Your e function is the same as List.member (though you'll still want to alias it). \$\endgroup\$
    – DLosc
    Jan 9, 2023 at 18:25
1
\$\begingroup\$

Hassium, 104 Bytes

func main(){r=[];i=[];foreach(e in d)if(!i.contains(e))i.add(e)else if(!r.contains(e))r.add(e);print(r)}

Run online and see expanded here

\$\endgroup\$
1
\$\begingroup\$

Python, 143 bytes

There are already some very good Python answers out there (see @dieters, @ppperry & @xnor answers) so I decided to take a different approach, have some fun with recursion and python lambda functions and see what could I come up with. This is not even close to the best answers here but it was fun to think.

The program takes the integer list as a parameter of function p and returns a list containing non-unique elements.

p=lambda i:[j for j in(lambda n:[]if len(n)<=1 else[(lambda x:x[0]if len([1 for o in x[1:]if x[0]==o])==1 else 'N')(n)]+p(n[1:]))(i) if j!='N']

Two line version for better readability:

p=lambda i:[j for j in(lambda n:[]if len(n)<=1 else[(lambda x:x[0]if 
len([1 for o in x[1:]if x[0]==o])==1 else 'N')(n)]+p(n[1:]))(i) if j!='N']

Short Explanation

The inner lambda takes a list x as a parameter and returns the first element of such list if it is repeated only once in the rest of the list (x[1:]). If not it returns 'N'.

The lambda in between the outer and inner lambdas is the one in charge of the recursive search. This returns a list containing the non-unique elements and plenty of 'N's. This is the one which takes the integer list as a parameter.

The outer lambda filters the resulting list getting rid of the unwanted 'N's.

Test cases

p([])
[]
p([-1,0,1])
[]
p([3, 0, 0, 1, 1, 0, 5, 3])
[3,0,1]
\$\endgroup\$
1
\$\begingroup\$

STATA, 18 bytes

bys v:drop if _n-2

Note that this requires the paid version of STATA.

Assumes the data is stored in a variable v and then the result will be in v at the end. It works by sorting by v and grouping duplicate values together. Each duplicate value will have at least two values, which means it can drop anything that is not the second element of each value. Third and subsequent elements will already be represented and the first element will either be unique or represented by the second.

For example, make a file a.b with data:

3
0
0
1
1
0
5
3

Then run the following code

insheet using a.b,clear
rename v1 v
bys v:drop if _n-2 //the actual code that does stuff
list v,noobs noheader
\$\endgroup\$
1
\$\begingroup\$

C# - 40

i.GroupBy(g=>g).SelectMany(s=>s.Skip(1))

Using select many to be able to use Skip and skip the first occurrence if it exists.

\$\endgroup\$
1
\$\begingroup\$

J, 12 14 13 bytes

~.d#~1<+/=/~d

Assumes the list is in d.

Explanation:

         =/~d   NB. compare each element in d to each element in d
       +/       NB. sum the columns (giving amount of occurrences)
     1<         NB. see which columns are greater than 1 (=not unique)
  d#~           NB. select those elements from d 
~.              NB. unique elements from that

If an anonymous function is OK as well, it can be shortened to 13 12:

~.#~1<+/"1@=
\$\endgroup\$
0
1
\$\begingroup\$

Jelly, 4 bytes, language postdates challenge

œ-QQ

Try it online!

Same algorithm as the accepted answer, just a shorter syntax.

\$\endgroup\$
1
  • \$\begingroup\$ This look so cryptic 0.o what is that first character? \$\endgroup\$
    – garg10may
    May 10, 2017 at 2:54
1
\$\begingroup\$

PHP, 75 bytes

function a($b){return array_unique(array_diff_assoc($b,array_unique($b)));}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Python 2.7, 36 bytes

list({x for x in i if i.count(x)>1})

Where i is the input

\$\endgroup\$
3
  • \$\begingroup\$ You'll need to make it a lambda function because snippets aren't allowed. \$\endgroup\$
    – Nissa
    Jun 6, 2018 at 17:45
  • \$\begingroup\$ 3 other people did the same thing, and OP doesn't seem to mind \$\endgroup\$
    – Khalil
    Jun 6, 2018 at 18:08
  • 6
    \$\begingroup\$ "Your answer may be a snippet which assumes the input to be stored in a variable". Note that this is not the default, but this question is old and the OP explicitly allowed it, so it is okay. \$\endgroup\$
    – mbomb007
    Jun 6, 2018 at 18:39
1
\$\begingroup\$

Kotlin, 41 bytes

{it.filter{v->it.count{it==v}>1}.toSet()}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 14 bytes

*.repeated.Set

Try it online!

Gets a Set of the repeated elements.

\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 60 bytes

f=>[...new Set(f.filter(e=>f.indexOf(e)!=f.lastIndexOf(e)))]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 43 bytes (another try)

a=>a.filter((t={},e=>!(1-(t[e]=++t[e]|0))))

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Burlesque, 9 bytes

peJNB\\NB

Try it online!

pe # Parse and push
J  # Duplicate
NB # Remove duplicate elements
\\ # Difference between nubbed and original lists
NB # Nub the difference
\$\endgroup\$
1
\$\begingroup\$

Perl 5, 18 bytes

Since a snippet is allowed here, the input is assumed to be in @F. The TIO link adds a little I/O around it.

grep++$k{$_}==2,@F

Try it online!

\$\endgroup\$
1
\$\begingroup\$

R, 24 bytes

names((t=table(v))[t>1])

Try it online!

Completely different approach to the previous R answer for the same number of bytes when written (as here) as a snippet with pre-defined variable v, but 4 bytes shorter as a full program (which, admittedly, isn't required by the challenge).
Outputs the non-unique elements as a vector of strings.


R, 25 bytes

(r=rle(sort(v)))$v[r$l>1]

Try it online!

One byte longer (and yet another approach) if you want to output as an integer vector.

\$\endgroup\$
1
\$\begingroup\$

Vyxal, 4 bytes

UÞ⊍U

Try it Online!

Multiset Symmetric difference is very powerful

\$\endgroup\$
1
\$\begingroup\$

05AB1E, 8 6 5 4 bytes

¢ÏKÙ

Try it online or verify all test cases.

Explanation:

      #  e.g. input=[1,2,3,2,1,1,6,4,5,6]
¢     # Count how many times each item of the (implicit) input-list occurs in the
      # (implicit) input-list
      #  → [3,2,1,2,3,3,2,1,1,2]
 Ï    # Only keep the values in the (implicit) input-list at the truthy (==1) indices
      #  → [3,4,5]
  K   # Remove those values from the (implicit) input-list, leaving all non-unique items
      #  → [1,2,2,1,1,6,6]
   Ù  # Uniquify that list of non-unique items
      #  → [1,2,6]
      # (after which the result is output implicitly)
\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 36 bytes

a=>a.filter(o=x=>a.a+a+a==(o[x]+=a))

Try it online!

\$\endgroup\$
1
\$\begingroup\$

jq, 22 bytes

[group_by(.)[][1:2][]]

Try it online!

Explanation:

[                    ]     # collect
                   []      # each
              [1:2]        # second item
            []             # from each
 group_by( )               # array of arrays of
          .                # identical values
\$\endgroup\$
1
\$\begingroup\$

Zsh coreutils, 15 bytes

sort|uniq -d|rs

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Pip -p, 11 bytes

UQ:_Ng>1FIg

Takes the integers as command-line arguments. Attempt This Online!

Explanation

UQ:_Ng>1FIg
          g  List of command-line arguments
        FI   Filter by this function:
   _N          The number of times this element appears in
     g         the list of command-line arguments
      >1       is greater than one
UQ:          Uniquify the resulting list
\$\endgroup\$
0
\$\begingroup\$

Arturo, 40 bytes

unique select b'x[1<size select b=>[=x]]

Try it

\$\endgroup\$
0
\$\begingroup\$

Japt, 7 bytes

ü lÉ cÎ

Try it (includes all test cases)

ü lÉ cÎ     :Implicit input of integer
ü           :Group & sort by value
  l         :Filter by length
   É        :  Minus 1
     c      :Flat map
      Î     :  First element
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.