text:
Find the first duplicated element
Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, your program / function may result in undefined behaviour.
Example:
For a = [2, 3, 3, 1, 5, 2], the output should be
firstDuplicate(a) = 3.
There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than the second occurrence of 2 does, so the answer is 3.
For a = [2, 4, 3, 5, 1], the output should be
firstDuplicate(a) = -1.
This is code-golf, so shortest answer in bytes wins.
BONUS: Can you solve it in O(n) time complexity and O(1) additional space complexity?

Comments are not for extended discussion; this conversation has been moved to chat.

Python 2, 34 bytes
O(n2) time, O(n) space
Saved 3 bytes thanks to @vaultah, and 3 more from @xnor!
lambda l:l[map(l.remove,set(l))<0]

Try it online!

It looks like lambda l:l[map(l.remove,set(l))<0] works, even though the order of evaluation is weird.

This doesn't return -1 when no duplicates are found without the 'footer code', does that code not count towards the bytes? I'm new to code golf, sorry if it's a basic question!

@Chris_Rands Beneath the question musicman did ask if exception is okay instead of -1 and OP said its okay and musicman's answer throws exception.

That took me a while to figure out. Well played. Getting the 0th element of l using the conditional after modifying it is really clever.

Does Python guarantee the time and space complexity of standard-library functions like set.remove?

@Draconis This is actually list remove, and set construction. The whole algorithm is O(n^2): list remove is O(n) and there are O(n) iterations. It uses O(n) extra space by constructing the set and the list constructed as a result of the map function

@musicman523 Of course, my mistake! I see what you're doing now. Clever.

JavaScript (ES6), 47 36 31 25 bytes
Saved 6 bytes thanks to ThePirateBay
Returns undefined if no solution exists.
Time complexity: O(n) :-)
Space complexity: O(n) :-(
a=>a.find(c=>!(a[-c]^=1))

How?
We keep track of already encountered values by saving them as new properties of the original array a by using negative numbers. This way, they can't possibly interfere with the original entries.
Demo

let f =

a=>a.find(c=>!(a[-c]^=1))

console.log(f([2, 3, 3, 1, 5, 2]))
console.log(f([2, 4, 3, 5, 1]))
console.log(f([1, 2, 3, 4, 1]))

25 bytes: a=>a.find(c=>!(a[-c]^=1))

@ThePirateBay Oh, of course. Thanks!

Just notice that Objects in JavaScript may not be implemented as hash table. Time complexity of accessing keys of some object may not be O(1).

Mathematica, 24 bytes
#/.{h=___,a_,h,a_,h}:>a&

Mathematica's pattern matching capability is so cool!
Returns the original List for invalid input.
Explanation
#/.

In the input, replace...
{h=___,a_,h,a_,h}

A List with a duplicate element, with 0 or more elements before, between, and after the duplicates...
... :>a

With the duplicate element.

Jelly, 5 bytes
Ṛœ-QṪ

Try it online!
How it works
Ṛœ-QṪ  Main link. Argument: A (array)

Ṛ      Yield A, reversed.
   Q   Unique; yield A, deduplicated.
 œ-    Perform multiset subtraction.
       This removes the rightmost occurrence of each unique element from reversed
       A, which corresponds to the leftmost occurrence in A.
    Ṫ  Take; take the rightmost remaining element, i.e., the first duplicate of A.

œ- removes the rightmost occurrences? TIL

This doesn't seem to return -1 for no duplicates. Throwing an exception is okay as per OP but I'm not sure if 0 is even though it's not in the range.

Pyth, 5 bytes
h.-Q{

Test suite
Remove from Q the first appearance of every element in Q, then return the first element.

@LuisMendo Ok thanks. Sorry for creating confusion, I should learn to read...

@Mr.Xcoder No, it's the OP's fault. That information should be in the challenge text, but just in a comment

Haskell, 35 bytes
f s(h:t)|h`elem`s=h|1<2=f(h:s)t
f[]

Try it online! Crashes if no duplicate is found.

Vyxal, 4 bytes
UÞ⊍h

Try it Online!
Takes the multi-set symmetric difference, which outputs the duplicate values in order that they occur. Outputs 0 if nothing is found.

Dyalog APL, 27 24 20 19 13 12 11 bytes
⊢⊃⍨0⍳⍨⊢=⍴↑∪

Now modified to not depend on v16! Try it online!
How? (With input N)

⊢⊃⍨... - N at this index:

⍴↑∪ - N with duplicates removed, right-padded with 0 to fit N
⊢= - Element-wise equality with N
0⍳⍨ - Index of the first 0. `

nevermind, I misread the question. not enough test cases though...

Sorry for misleading you, I also misread the question.

Looks like 36 bytes to me.

Oh god, iota underbar isn't in ⎕AV, is it?

@Zacharý Right, Classic translates it to ⎕U2378  when loading. Try it online!

You may throw an error instead of returning ¯1

That is a very clever solution. +1.

I guess I'm in the array (or at least vector) oriented way of thinking now!

In the link the solution result enclosed in () where above is not enclose; in my cellphone I not know how to run that in tio ( dialog Unicode and classic)

It's sort of like an anonymous/lambda function in JavaScript/Python. You need but parentheses to call it, but the actual function doesn't require parentheses.

Jelly, 6 bytes
xŒQ¬$Ḣ

Try it online!
Returns the first duplicate, or 0 if there is no duplicate.
Explanation
xŒQ¬$Ḣ  Input: array M
    $   Operate on M
 ŒQ       Distinct sieve - Returns a boolean mask where an index is truthy
          for the first occurrence of an element
   ¬      Logical NOT
x       Copy each value in M that many times
     Ḣ  Head

It's golfier to use indexing like this: ŒQi0ị.

@EriktheOutgolfer If there are no duplicates, i0 would return 0, where ị would index and return the last value of the input instead of 0.

Japt, 7 bytes
æ@bX ¦Y

Test it online!
Explanation
 æ@   bX ¦ Y
UæXY{UbX !=Y}  Ungolfed
               Implicit: U = input array
UæXY{       }  Return the first item X (at index Y) in U where
     UbX         the first index of X in U
         !=Y     is not equal to Y.
               In other words, find the first item which has already occured.
               Implicit: output result of last expression

Alternatively:
æ@¯Y øX

Test it online!
Explanation
 æ@   ¯ Y øX
UæXY{Us0Y øX}  Ungolfed
               Implicit: U = input array
UæXY{       }  Return the first item X (at index Y) in U where
     Us0Y        the first Y items of U (literally U.slice(0, Y))
          øX     contains X.
               In other words, find the first item which has already occured.
               Implicit: output result of last expression

Brachylog, 5 bytes
a⊇=bh

Try it online!
Explanation
a⊇=bh  Input is a list.
a      There is an adfix (prefix or suffix) of the input
 ⊇     and a subsequence of that adfix
  =    whose elements are all equal.
   b   Drop its first element
    h  and output the first element of the rest.

The adfix built-in a lists first all prefixes in increasing order of length, then suffixes in decreasing order of length.
Thus the output is produced by the shortest prefix that allows it, if any.
If a prefix has no duplicates, the rest of the program fails for it, since every subsequence of equal elements has length 1, and the first element of its tail doesn't exist.
If a prefix has a repeated element, we can choose the length-2 subsequence containing both, and the program returns the latter.

Another 5 bytes solution: a⊇Ċ=h, which only looks at length-2 subsets.

Retina, 26 24 bytes
1!`\b(\d+)\b(?<=\b\1 .*)

Try it online! Explanation: \b(\d+)\b matches each number in turn, and then the lookbehind looks to see whether the number is a duplicate; if it is the 1st match is ! output, rather than the count of matches. Unfortunately putting the lookbehind first doesn't seem to work, otherwise it would save several bytes. Edit: Added 7 bytes to comply with the -1 return value on no match. Saved 2 bytes thanks to @MartinEnder.

For the record, the lookaround won't backtrack. This prevents this from working if you try to put it before. I've made this mistake many times, and Martin always corrects me.

I got 30 bytes by using a lookahead instead of a lookbehind. Also, the rules now say you don't need to return -1.

@ValueInk But the correct answer for that test case is 3...

OH. I misread the challenge, whoops

Python 3, 94 92 bytes
O(n) time and O(1) extra memory.
def f(a):
 r=-1
 for i in range(len(a)):t=abs(a[i])-1;r=[r,i+1][a[t]<0>r];a[t]*=-1
 return r

Try it online!
Source of the algorithm.
Explanation
The basic idea of the algorithm is to run through each element from left to right, keep track of the numbers that have appeared, and returning the number upon reaching a number that has already appeared, and return -1 after traversing each element.
However, it uses a clever way to store the numbers that have appeared without using extra memory: to store them as the sign of the element indexed by the number. For example, I can represent the fact that 2 and 3 has already appeared by having a[2] and a[3] negative, if the array is 1-indexed.

What would this do for i where a[i] > n?

@Downgoat read the question again.

The question says 1 to a.length but for a[i]= a.length wouldn't this go out of bounds?

@Downgoat t=abs(a[i])-1=a.length-1

Oh duh sorry thanks

Note from feersum: "solution is cheating because it uses integers 1 bit larger than the input."

-2 bytes with enumerate

89 bytes by having the initial definition of r=-1 as a default argument

APL (Dyalog), 20 bytes
⊃n/⍨(,≢∪)¨,\n←⎕,2⍴¯1

Try it online!
2⍴¯1 negative one reshaped into a length-two list
⎕, get input (mnemonic: console box) and prepend to that
n← store that in n
,\ prefixes of n (lit. cumulative concatenation)
(…)¨ apply the following tacit function to each prefix
 , [is] the ravel (just ensures that the prefix is a list)
 ≢ different from
 ∪ the unique elements[?] (i.e. is does the prefix have duplicates?)
n/⍨ use that to filter n (removes all elements until the first for which a duplicate was found)
⊃ pick the first element from that

Wow, you got beat three times. Still, +1. And can you add an explanation of how this works?

@Zacharý Apparently I just needed to get the ball rolling. Here you go.

@Zacharý Eventually, I managed to beat them all.

Perl 6, 13 bytes
*.repeated[0]

Try it

Explanation

The * is in a Term position so the whole statement is a WhateverCode lambda.
The .repeated is a method that results in every value except for the first time each value was seen.
say [2, 3, 3, 3, 1, 5, 2, 3].repeated.perl; # (3, 3, 2, 3).Seq
#   (      3, 3,       2, 3).Seq

[0] just returns the first value in the Seq.
If there is no value Nil is returned.
(Nil is the base of the Failure types, and all types are their own undefined value, so Nil different than an undefined value in most other languages)

Note that since the implementation of .repeated generates a Seq that means it doesn't start doing any work until you ask for a value, and it only does enough work to generate what you ask for.
So it would be easy to argue this has at worst O(n) time complexity, and at best O(2) time complexity if the second value is a repeat of the first.
Similar can probably be said of memory complexity.

APL (Dyalog), 11 bytes
As per the new rules, throws an error if no duplicates exist.
⊢⊃⍨⍬⍴⍳∘≢~⍳⍨

Try it online!
⍳⍨ the indices of the first occurrence of each element
~ removed from
⍳∘≢ of all the indices
⍬⍴ reshape that into a scalar (gives zero if no data is available)
⊃⍨ use that to pick from (gives error on zero)
⊢ the argument

Well, yeah, when the rules are changed, of course you can beat them all!

Well, I tied you.

APL, 15
{⊃⍵[(⍳⍴⍵)~⍵⍳⍵]}

Seems like we can return 0 instead of -1 when there are no duplicates, (thanks Adám for the comment). So 3 bytes less.
A bit of description:
⍵⍳⍵         search the argument in itself: returns for  each element the index of it's first occurrence
(⍳⍴⍵)~⍵⍳⍵   create a list of all indexes, remove those found in ⍵⍳⍵; i.e. remove all first elements
⊃⍵[...]     of all remaining elements, take the first. If the array is empty, APL returns zero

For reference, old solution added -1 to the list at the end, so if the list ended up empty, it would contain -1 instead and the first element would be -1.
{⊃⍵[(⍳⍴⍵)~⍵⍳⍵],¯1}

Try it on tryapl.org

You may return a zero instead of ¯1, so {⊃⍵[(⍳⍴⍵)~⍵⍳⍵]} should do.

PHP, 56 44 38 32 bytes
for(;!${$argv[++$x]}++;);echo$x;

Run like this:
php -nr 'for(;!${$argv[++$x]}++;);echo$x;' -- 2 3 3 1 5 2;echo
> 3

Explanation
for(
  ;
  !${                 // Loop until current value as a variable is truthy
    $argv[++$x]       // The item to check for is the next item from input
  }++;                // Post increment, the var is now truthy
);
echo $x;              // Echo the index of the duplicate.

Tweaks

Saved 12 bytes by using variables instead of an array
Saved 6 bytes by making use of the "undefined behavior" rule for when there is no match.
Saved 6 bytes by using post-increment instead of setting to 1 after each loop

Complexity
As can be seen from the commented version of the code, the time complexity is linear O(n). In terms of memory, a maximum of n+1 variables will be assigned. So that's O(n).

Thanks for not using a weird encoding. But you should add the error_reporting option to the byte count (or use -n, which is free).

We've been here before. PHP notices and warnings are ignorable. I might as well pipe them to /dev/null, which is the same.

I tend to remember the wrong comments. :) Isn´t this O(n)?

Yes it's linear

How is that O(1) for additional space? You're literally assigning a new variable per n, which is O(n)

@Xanderhall, I might have misunderstood, but doesn't the question say additional space? I took that to mean O(n) was assumed to be necessary anyway.

The storage for the initial list hasO(n) space complexity, yes. However, if you're say, storing every single value in a separate list to check if you've passed them, that's O(n) additional space complexity. What you're doing is effectively the same, but without the 'list' construct. In your worst case (say, [1, 2, ..., n, 1] you'll end up with n variables created additionally, which is O(n) space complexity

@Xanderhall The list is actually even worse than O(n), its O(n log n) because each number requires at most O(log n) bits to store and there are n of them. I don't understand php so I can't comment on this answers complexity directly but  if it stores up to n+1 values that can be as large as n then it has O(n log n) space complexity.  It only has O(n) space complexity if each variable is some fixed number of bits.

@WheatWizard, not at all. They are INTs (basically booleans) that will never be anything other than 0, 1 or 2. And the 2 case is not used, it's just a simplification of the code

@Xanderhall, I removed the statement as I'm not sure now what was meant.

J, 12 bytes
,&_1{~~:i.0:

Try it online!
Explanation
,&_1{~~:i.0:  Input: array M
      ~:      Nub-sieve
          0:  The constant 0
        i.    Find the index of the first occurrence of 0 (the first duplicate)
,&_1          Append -1 to M
    {~        Select the value from the previous at the index of the first duplicate

K (ngn/k), 11 bytes
*(~':?',\)#

Try it online!
*(~':?',\)#
 (       )#   keep the elements where the left function returns true
              (when applied to the whole array):
       ,\       prefixes
     ?'         uniquify each
  ~':           is it the same as previous?
*             first element

MATL, 8 bytes
&=Rsqf1)

Gives an error (without output) if no duplicate exists.
Try at MATL Online!
Explanation
&=   % Implict input. Matrix of all pairwise equality comparisons
R    % Keep the upper triangular part (i.e. set lower part to false)
s    % Sum of each column
q    % Subtract 1
f    % Indices of nonzero values
1)   % Get first. Gives an error is there is none. Implictly display

J, 17 16 bytes
(*/{_1,~i.&0)@~:

How?
(*/{_1,~i.&0)@~:

             @~: returns the nub sieve which is a vector with 1 for the first occurrence of an element in the argument and 0 otherwise

        i.&0     returns the first index of duplication

    _1,~         appends _1 to the index

 */              returns 0 with duplicates (product across nub sieve)

     {           select _1 if no duplicates, otherwise return the index

R, 28 bytes
(x=scan())[duplicated(x)][1]

Try it online!

I think you can now return NA for missing values since the spec has changed; so (x=scan())[duplicated(x)][1] is perfectly valid.

R, 34 bytes
c((x=scan())[duplicated(x)],-1)[1]

Cut a few characters off the answer from @djhurio, don't have enough reputation to comment though.

oh...I didn't see this answer; this is good for the prior spec when missing values required -1 but with the new spec, I managed to golf it down even more. This is still solid and it's a different approach from the way he did it, so I'll give you a +1!

Java 8, 82 78 76 bytes No longer viable, 75 67 64 bytes below in edit
As a lambda function:
a->{Set<Long>s=new HashSet<>();for(long i:a)if(!s.add(i))return i;return-1;}

Probably can be made much smaller, this was very quick.
Explanation:
a->{                                //New lambda function with 'a' as input
    Set<Long>s=new HashSet<>();     //New set
    for(long i:a)                   //Iterate over a
        if(!s.add(i))               //If can't add to s, already exists
            return i;               //Return current value
        return-1;                   //No dupes, return -1
}

*Edit*
75 67 64 bytes using the negation strategy:
a->{int i=0,j;while((a[j=Math.abs(a[i++])-1]*=-1)<0);return++j;}

Try it online!
(-3 bytes thanks to @Nevay)
Explanation:
a->{                                         //New lambda expression with 'a' as input
    int i=0,j;                               //Initialise i and declare j
    while((a[j=Math.abs(a[i++])-1]*=-1)<0);  //Negate to keep track of current val until a negative is found
    return++j;                               //Return value
}

Loops over the array, negating to keep track. If no dupes, just runs over and throws an error.
Both of these work on O(n) time and O(n) space complexity.

It's worth noting that this will need to be assigned to a lambda returning Number, since i is a long and -1 is an int.

@Jakob Not necessary, -1 being an int will automatically be cast to a long without explicitly specifying the cast

It will cast implicitly to long, but not to Long as required for the lambda to be assigned to a Function. Did you test it? Regardless, that solution can be replaced with your new one.

You can use raw types Set s=new HashSet(); to save 7 bytes. (Besides: afaik the import of java.util.*; has to be included into the byte count -> +19 bytes.) The return statement can be return++j, the if-statement can be removed a->{int i=0,j;for(;(a[j=Math.abs(a[i++])-1]*=-1)<0;);return++j;} (-3 bytes).

Dyalog APL Classic, 18 chars
Only works in ⎕IO←0.
     w[⊃(⍳∘≢~⍳⍨)w←¯1,⎕]

Remove from the list of indices of the elements of the argument with a prepended "-1" the list indices of its nub and then pick the first of what's left. If after the removal there only remains an empty vector, its first element is by definition 0 which is used to index the extended argument producing the desired -1.

Um... what's with the random leading spaces? +1 for outgolfing me by one byte.

You may throw an error instead of returning ¯1, so you can remove ¯1, and use ⎕IO←1.

Ruby, 28 36 bytes
Misunderstood the challenge the first time. O(n) time, O(n) space.
->a{d={};a.find{|e|b=d[e];d[e]=1;b}}

Try it online!

Java (OpenJDK 8), 65 117 109 bytes

Previous 65 byte solution:
r->{for(int a,b=0,z,i=0;;b=a)if((a=b|1<<(z=r[i++]))==b)return z;}

New solution. 19 bytes are included for import java.math.*;
-8 bytes thanks to @Nevay
r->{int z,i=0;for(BigInteger c=BigInteger.ZERO;c.min(c=c.setBit(z=r[i++]))!=c;);return z;}

Try it online!
Edit
The algorithm in my original program was fine, but the static size of the datatype used meant that it broke fairly quickly once the size went above a certain threshold.
I have changed the datatype used in the calculation to increase the memory limit of the program to accommodate this (using BigInteger for arbitrary precision instead of int or long). However, this makes it debatable whether or not this counts as O(1) space complexity.
I will leave my explanation below intact, but I wish to add that I now believe it is impossible to achieve O(1) space complexity without making some assumptions.
Proof
Define N as an integer such that 2 <= N .
Let S be a list representing a series of random integers [x{1}, ..., x{N}], where x{i} has the constraint 1 <= x{i} <= N.
The time complexity (in Big-O notation) required to iterate through this list exactly once per element is O(n)
The challenge given is to find the first duplicated value in the list. More specifically, we are searching for the first value in S that is a duplicate of a previous item on the list.
Let p and q be the positions of two elements in the list such that p < q and x{p} == x{q}. Our challenge becomes finding the smallest q that satisfies those conditions.
The obvious approach to this problem is to iterate through S and check if our x{i} exists in another list T:
    If x{i} does not exist in T, we store it in T.
    If x{i} does exist in T, it is the first duplicate value and therefore the smallest q, and as such we return it.
This space efficiency is O(n).
In order to achieve O(1) space complexity while maintaining O(n) time complexity, we have to store unique information about each object in the list in a finite amount of space. Because of this, the only way any algorithm could perform at O(1) space complexity is if:
    1. N is given an upper bound corresponding to the memory required to store the maximum number of possible values for a particular finite datatype.
    2. The re-assignment of a single immutable variable is not counted against the complexity, only the number of variables (a list being multiple variables).
    3. (Based on other answers) The list is (or at least, the elements of the list are) mutable, and the datatype of the list is preset as a signed integer, allowing for changes to be made to elements further in the list without using additional memory.
1 and 3 both require assumptions and specifications about the datatype, while 2 requires that only the number of variables be considered for the calculation of space complexity, rather than the size of those variables. If none of these assumptions are accepted, it would be impossible to achieve both O(n) time complexity and O(1) space complexity.
Explanation
Whoo boy, this one took an embarrassingly long time to think up a bit of brain power.
So, going for the bonus is difficult. We need both to operate over the entire list exactly once and track which values we've already iterated over without additional space complexity.
Bit manipulation solves those problems. We initialize our O(1) 'storage', a pair of integers, then iterate through the list, OR-ing the ith bit in our first integer and storing that result to the second.
For instance, if we have 1101, and we perform an OR operation with 10, we get 1111. If we do another OR with 10, we still have 1101.
Ergo, once we perform the OR operation and end up with the same number, we've found our duplicate. No duplicates in the array causes the program to run over and throw an exception.

Also, your second test includes the number 100, but thats impossible since the array itself is only 5 long

Also, this fails since an int doesn't have enough storage.

@SchoolBoy Good catch. My only problem is that there doesn't seem to be any upper limit on the size of the array, so I can't realistically change my code to solve memory issues.

@Xanderhall True, but i feel like 32 (or if you use a long, 64) numbers is too little :p. Either way, imposing a limit on the input, and then allocating the maximum memory needed and calling it O(1) memory is just a cheat. It is still O(n) since if the size of the input increased, so would this upper bound to the memory. Which is also why I think it is impossible to create an O(n) O(1) algorithm

@Xanderhall P.S. I'm getting close to your 65, I'm at 67 bytes :p

You don't need d, the if-statement can be removed r->{int z,i=0;for(BigInteger c=BigInteger.ZERO;!c.equals(c=c.setBit(z=r[i++])););return z;} (91+19 bytes). If you don't mind to depend on the implementation rather than on the api, you can use c.min(c=c.setBit(z=r[i++]))!=c instead of #equals to save another byte.

I may not be fully understanding the final part about bit ORing, but just because your current OR product ORed with this new number is the same, doesn't mean it's been in your list before.  For example, if your list was [12, 4, 12], you would do 1100 | 0100 = 1100 but 4 isn't a duplicate.  Even the example [2, 4, 3, 5, 1] fails since by the time you get to 5 your OR product will be 010 | 100 | 011 = 111, which when ORed with 101 is still 111.  Maybe I'm just not understanding what you're trying to say...

You're not ORing the nth number found in the list with the storage, you're ORing the nth byte in the storage. ie: in [1, 2, 3, 2, 3], you would get 001 (first bit), 011(second bit), 111(third bit), 111(second bit again), then 2 would be returned.

I would say that although the input is not specifically limited, imposing a limit like 32 on it is harsh, but using longs or ints instead of BigIntegers should be fine

I know it's been a while, but you can golf import java.math.*;BigInteger c=BigInteger.ZERO; to java.math.BigInteger t=null,c=t.ZERO; for -11 bytes.

Husk, 4 bytes
←Ṡ-u

Returns 0 if no input contains no duplicate, try it online!
Explanation
←Ṡ-u  -- takes a list X as input & returns 0 or first duplicate
 Ṡ-   -- compute X - ...
   u  --       ...   deduplicate X
←     -- get first element or 0 if empty

Haskell, 34 bytes
import Data.List
f x=head$x\\nub x

Try it online! For an input x = [2,3,3,1,5,2], nub x removes duplicates [2,3,1,5] and x\\nub x removes the elements of nub x from x, thus keeping the duplicates [3,2]. head returns the first element of hat list.

Point-free is the same byte count: head.((\\)<*>nub).

Nekomata + -1, 4 bytes
pƆᵗf

Attempt This Online!
pƆᵗf
p       Find a prefix of the input
 Ɔ      Split it into the last element and the rest
  ᵗf    Check if the last element is in the rest, and return it if it is

-1 prints the first possible result, or nothing if there is no result.

05AB1E, 5 bytes
.ΔkNÊ

Outputs -1 if there are no duplicated items, like in the challenge examples.
Try it online or verify both test cases.
Explanation:
.Δ     # Find the first element in the (implicit) input-list where the following is
       # truthy, or -1 if none are truthy:
  k    #  Get the first index of the current integer in the (implicit) input-list
   NÊ  #  Check whether it's NOT equal to the current find_first index
       # (after which the result is output implicitly as result)

What was wrong with the original "Outputs an empty string if there are no duplicates" 4-byte version?

@DominicvanEssen It outputs the first integer that occurs more than once, instead of the first result that occurred before. So for the first test case ([2,3,3,1,5,2]) it would incorrectly result in 2 instead of 3.

Ah, thanks for clarifying.  (Not that I ought to have been skulking around in the edit history...)

C#, 145 bytes
using System.Linq;a=>{var d=a.Where(n=>a.Count(t=>t==n)>1);return d.Select((n,i)=>new{n,i}).FirstOrDefault(o=>d.Take(o.i).Contains(o.n))?.n??-1;}

Probably a lot shorter way to do this in C# with a simple loop but I wanted to try it with Linq.
Try it online!
Full/Formatted version:
namespace System.Linq
{
    class P
    {
        static void Main()
        {
            Func<int[], int> f = a =>
            {
                var d = a.Where(n => a.Count(t => t == n) > 1);
                return d.Select((n, i) => new { n, i }).FirstOrDefault(o => d.Take(o.i).Contains(o.n))?.n ?? -1;
            };

            Console.WriteLine(f(new[] { 2, 3, 3, 1, 5, 2 }));
            Console.WriteLine(f(new[] { 2, 4, 3, 5, 1 }));

            Console.ReadLine();
        }
    }
}

Here is the simple loop version. But I like the Linq version much more.

@LiefdeWen Post it as an answer :) Though I do usually like Linq better too :) Might be able to get it shorter with Linq too but I'm now sure.

Nah, this question is overpopulated and I would rather you get the up-votes for this question.

Haskell, 78 69 bytes
 fst.foldl(\(i,a)(j,x)->(last$i:[j|i<0,elem x a],x:a))(-1,[]).zip[1..]

Try it online!
Saved 9 bytes thanks to @nimi
A basic path through the list. If the current element has not yet been seen (i<0) and is in the accumulator list (elem x a) then store the current index. Else, keep the index -1. In any case, add the current element to the accumulator list.
EDIT: I did not read the question carefully enough: this code outputs the index of the second element of a duplicate element.

You can use the "Shorter Conditional" from our "Tips for golfing in Haskell": \ ... ->(last$i:[j|i<0,elem x a],x:a). Also: no need for the f=, because unnamed functions are allowed.

@nimi thanks for the tip!

PROLOG (SWI), 54 + 3 = 57 bytes
f([H|_],L,H):-member(H,L).
f([H|T],L,X):-f(T,[H|L],X).

+3 bytes because it requires an empty list as its second argument:
f([5,3,2,1,2,3,5],[],X)

will unify X to the first duplicate value in the list.
Try it online!
Here's the basic algorithm: we have the list to parse, and an accumulator list that starts empty. For each element in the list: pop that element. If it is in the accumulator, return the element. Else, put it in the accumulator.

Python 2, 71 65 bytes
Returns None if there is no duplicate element
Edit: -6 bytes thanks to @musicman523
def f(n):
 for a in n:
	u=-abs(a)
	if n[u]&lt0:return-u
	n[u]=-n[u]
Try it online!
O(n) time complexity, O(n) space complexity, O(1) auxiliary space.
As the input list uses O(n) space, the space complexity is bound by this. Meaning we cannot have a lower space complexity than O(n)
Does modify the original list, if this is not allowed we could do it in the same complexity with 129 bytes
Explanation
Since every element is greater than 0 and less than or equal to the size of the list, the list has for each element a, an element on index a - 1 (0 indexed). We exploit this by saying that if the element at index i is negative, we have seen it before.
For each element a in the list n, we let u be negative the absolute value of a. (We let it be negative since python can index lists with negative indices, and we would otherwise need to do u=abs(a)-1) If the element at index u in the list is negative, we have seen it before and can therefore return -u (to get the absolute value of a, as all elements are positive). Else we set the element at index u to be negative, to remember that we have seen an element of value a before.

Nice job! 65 bytes

Are you sure this is O(1) in memory?  You are still using n bits of memory to store what numbers have already been visited, even though the bits are in the sign.  It seems to me that this is O(n) in disguise

Technically this uses O(n) space - the n sign bits. If the array can only hold values between 1 and n, like how it was given, then it obviously doesn't work.

This really just comes down to the representation you choose for the numbers. If unsigned numbers are used, then this is O(n) auxiliary space. If signed numbers are used, then the sign bit is already there, meaning O(1) auxiliary space.

I agree with you there.  I personally would let you slide using signed integers as long as you didn't use the sign bit, it should be about the algorithm not the technicalities of the system.  That being said I do think if you are going to use the sign bits you have to count them.  I think this answer is pretty clever.  If I any votes left today I would upvote it to counteract the downvote.

I think n[u]*=-1 would work to save two bytes.

Jelly, 4 bytes
ŒQi0

Try it online!
In case that all elements are unique, this returns 0 (undefined behavior).

K4, 12 bytes
Solution:
*<0W^*:'1_'=

Example:
*<0W^*:'1_'=2 3 3 1 5 2
3

Explanation:
Returns first item in the list for unique lists otherwise returns first dupe:
*<0W^*:'1_'= / the solution
           = / group the list, e.g. 2 3 1 5!(0 5;1 2;,3;,4)
        1_'  / drop first from each value, e.g. 2 3 1 5!(,5;,2;`long$();`long$())
     *:'     / first (*:) each ('), e.g. 2 3 1 5!5 2 0N 0N
  0W^        / fill (^) nulls with infinity (0W), e.g. 2 3 1 5!5 2 0W 0W
 <           / sort keys based on values, e.g. 3 2 1 5
*            / take the first, e.g. 3

Alice, 21 bytes
/o/
\iHQ@/w].(?~!&WK?

Try it online!
Explanation
The main idea is to store each value we've encountered on the tape and then use the search command to check whether the current value has already been written to the tape. It's important here that the tape is initially completely filled with -1s.
/      Switch to Ordinal mode.
i      Read all input as a string.
/      Switch back to Cardinal mode.
H      Take the absolute value of the top stack element. This doesn't really do
       anything to the numbers, because they're all positive anyway, but
       it forces Alice to convert the input string to individual integer
       values it contains, thus splitting the string.
/      Switch to Ordinal mode.
Q      Reverse the stack so that the first input is on top.
/      Switch back to Cardinal mode.
w      Push the current IP position onto the return address stack. This marks
       the beginning of the main loop.
         Call the current value on top of the stack X.
  ]      Advance the tape head (unnecessary on the first iteration, but
         we need to do it between iterations).
  .      Duplicate X.
  (      Search left of the tape head for X. If X isn't found nothing happens
         and we remain on a -1. Otherwise, the tape head jumps to that
         earlier occurrence.
  ?      Retrieve the value under the tape head. If X is new, this will be
         -1. Otherwise, it will be X. Call this value Y.
  ~!     Store X in the current cell.
  &W     Discard Y values from the return address stack. If Y is negative,
         this does nothing, otherwise it discards the one return address we
         have there, terminating the loop.
$K     If the return address is still there, jump back to the w to process
       the next element. Otherwise continue.
?      Retrieve X.
\      Switch to Ordinal mode.
o      Output the result.
H      Trim, does nothing.
@      Terminate the program.

I've got an alternative solution at the same byte count:
/o/
\iHQ@/w.!(]?h$WK[?

I also had a solution where I used the tape as a lookup table, storing at each index X whether X had already been seen in the sequence, but it ended up being a byte longer (it's conceptually easier, but moving the tape head to position X from an arbitrary positive position requires five bytes with q&[&]).

x86-16 machine code, 22 bytes
00000000: 33c0 9992 d792 d7d7 3bc2 75f7 33c0 d792  3.......;.u.3...
00000010: d73b c275 f9c3                           .;.u..

Listing:
33 C0       XOR  AX, AX         ; AL = 0, starting hare position
99          CWD                 ; DL = 0, starting tortoise position
        L1:
92          XCHG AX, DX         ; swap t/h in AL
D7          XLAT                ; tortoise crawl to next
92          XCHG AX, DX         ; swap t/h in AL
D7          XLAT                ; hare hops
D7          XLAT                ; hare hops again
3B C2       CMP  AX, DX         ; did they land on same element?
75 F7       JNZ  L1             ; loop if not
33 C0       XOR  AX, AX         ; start tortoise at beginning to find first index match
        L2:
D7          XLAT                ; tortoise crawls
92          XCHG AX, DX         ; swap t/h in AL
D7          XLAT                ; hare hops
3B C2       CMP  AX, DX         ; did they land on same element?
75 F9       JNZ  L2             ; loop if not
C3          RET                 ; return to caller

The old Tortoise and Hare (cycle detection) algorithm... using as many 1 byte opcodes as possible.

Time complexity: O(2n), linear
Space complexity: O(1) (uses no additional  memory - all work done in CPU registers)

As a callable function, input pointer to list at [BX], output index in AL.
Test results using DOS DEBUG:

Factor, 21 bytes
[ duplicates ?first ]

Try it online!
Returns f in case the input has no duplicates. This is idiomatic for Factor rather than -1. Let me know if that's not allowed and I can fix it (i.e. make it much longer).

duplicates Return only the elements that repeat in a sequence (in order).
?first Return the first element of a sequence or f if the sequence is empty.

TI-Basic, 39 bytes
Prompt A
ʟA
Ans(1+sum(not(cumSum(seq(I≠1+sum(not(cumSum(Ans=Ans(I)))),I,1,dim(Ans

Output is stored in Ans and is displayed at the end. Throws an error if there are no duplicates.

Gema, 46 characters
<N>=@cmpn{${$0;};;;;$0@end}@set{$0;1}
?=
\Z=-1

Sample run:
bash-5.1$ gema '<N>=@cmpn{${$0;};;;;$0@end}@set{$0;1};?=;\Z=-1' <<< '[2, 3, 3, 1, 5, 2]'
3

bash-5.1$ gema '<N>=@cmpn{${$0;};;;;$0@end}@set{$0;1};?=;\Z=-1' <<< '[2, 4, 3, 5, 1]'
-1

Try it online!

K (ngn/k), 18 bytes
{x@({+/y=x}':x)?1}

Try it online!
A little bit lengthy, but works nonetheless. I still can't fully understand how this even works (especially the counting duplicates section) and I'm on mobile, so explanations will be edited later.

Zsh, 48 bytes
for n;A+=($@[(in:2:)$n]);<<<$@[`printf ${(o)A}`]

Try it online!
Input is via argument array $@.
A is an array of indexes of secondary duplicates.
printf ${(o)A} sorts A leaving only the lowest index.
<<<$@[ ] prints the argument at that index.

Nibbles, 3 bytes (6 nibbles)
/-$`$$

Attempt This Online!
Outputs 0 if there are no duplicated elements.
/-$`$$
 -      # remove
   `$   # unique elements of
     $  # input
  $     # from the input
        # (this leaves only duplicated elements,
        # in their original order);
/       # get the first element
        # (actually, fold returning left-hand element at each step,
        # but result is to return left-most element)

5 bytes to instead return -1 when there are no duplicated elements, as in the example and initial spec:  /:-$`$$-1

Axiom 96, bytes
g(a:List INT):INT==(for i in 2..#a repeat(for j in 1..i-1 repeat if a.i=a.j then return a.i);-1)

it is O(n^2)

Javascript, 54 bytes
a=>(b=[],a.find(e=>b.includes(e)?e:(b.push(e),0))||-1)

Uses another array to keep track of the already encountered values.

05AB1E, 16 bytes
ε¹SsQƶ0K1è}W<¹sè

Try it online!

Python 2, 115 113 bytes
a,i,k=input(),0,[]
while 1:
	if i==len(a):print-1;break
	elif a[i]not in k:k+=[a[i]]
	else:print a[i];break
	i+=1

Try it online!

I might be wrong, but doesn't the fact that your list k can have up to n elements make this a O(n) space complexity solution?

Not to mention the fact that check a[i] in k may take O(n) (unless Python arrays is special)

@ValueInk you are correct. my bad.

This is actually O(n log n) in space complexity, because the numbers in your k take O(log n) memory to store each and there are as many as n of them.

I should think user202729 is correct too, making your algorithm O(n^2) time complexity. The while loop is O(n) (early break or not), and so is the in call.

@WheatWizard Wait what? Why the log n? k is filled with integers which are O(1) each, right? Their magnitude is not dependent on n.

@Sanchises The integers are dependent on n.  Since integers can always be as large as the length of the array, each will take (in the worst case) O(log n) bits to represent.  Meaning we have an array of length of up to n filled with items of up to log n bits.

@WheatWizard Ah yes, I didn't read that. But that means that we cannot even store one integer in O(1) extra space complexity, so I should think the author did not account for that when making the bonus.

@Sanchises You have a point, and I think you are probably correct however we should probably aim to be correct even if we think the author made a mistake. :)

Spaces, print -1=>print-1, a[i] not in=>a[i]not in.

Perl 5, 36 + 2 (-ap) = 38 bytes
Runs in O(n) time.
$s{$_}=1while!$s{$_=shift@F};$_||=-1

Try it online!
Takes the input list space separated.

C (gcc), 98 bytes
0-indexed
Takes a space separated list of integers. returns i < n on a successful match and i == n on failure.
time complexity is O(n^2) yuck!
space complexity is O(1)
program-name.exe 58 77 57 7 75 44 29 97 92 59 36 52 95 87 44 24 47 18 34 22
Returns 14  (the two 44s)

Golfed

i=1,j;main(int c,char**v){for(;i<c;i++)for(j=i-1;j;j--)if(!strcmp(v[i],v[j]))goto f;f:return i-1;}

Try it online!
Ungolfed
i=1,j;
main(int c, char**v){
    for(;i < c; i++)
        for(j=i-1; j; j--)
            if(!strcmp(v[i], v[j]))
                goto f;
    f:
    return i-1;
}

Time complexity is related to looping.  A loop that touches every slot of an array with size n is said to have time complexity O(n).  Since you have a for loop inside another one, and each one is on the order O(n) (since they aren't always a constant range), your program has time complexity O(n^2).  For more info about Big O Notation, check out this Wikipedia page.

I see, thanks for the info. I updated my answer.

The time complexity should be O(n^2 log m), where n is how many numbers there are, and m is the largest number given. This is because strcmp takes linear time with respect to the number of characters in each string

Python 2, 59 bytes, O(n) time, O(n) memory
a=input()
i=0
for x in a:
 if i&1<<x:print x;break
 i^=1<<x

Try it online!
This does one pass of the list. Thus is O(n)  For memory it stores a integer i, which has bits representing which numbers have already been visited.  If a number has already been visited we output, otherwise we turn the bit on.  If no matches are found we do nothing.
This makes a slight improvement over the naïve way which requires copying the list at the cost of O(n log n) memory.

i needs to have n bits, so I think it should be O(n) memory. (i can take values up to 2**n - 2 even if there is a duplicate.)

However, it is better than a copy of the list, as a copy of the list in general needs log(n)*n bits if we are equally as strict (log(n) bits per item times n items).

@tehtmi Fixed now, thanks for that.  I have trouble with space complexity.

PowerShell, 93 bytes
$c=0..$a.Count;$i=0;$r=($a|%{$i++;if($c[$_]++ -ne $_){$i}});if($r.Count -gt 0){$r[0]}else{-1}

Try it online!

JavaScript (Node.js), 81 bytes
Time complexity is O(n) !!!!
Space complexity is O(1) !!!!
a=>a.reduce((r,e,i)=>r?r:(a[(e<0?~e:e)-1]>0?((a[(e<0?~e:e)-1]^=-1)?0:0):i+2),0)-1

Try it online!
Strategy
This algorithm leverages the fact that indexes are positive but numbers in javascript are signed.  Also, zeros are not allowed input.  As long as the array is not longer than 2^31, this solution will work. I double the use of the original array as my lookup array -- marking a visited number by switching the value at that index with its 2's compliment.

We've had this discussion on another answer using a similar algorithm.  Although it may appear that this is O(1) you are actually using O(n) memory.  Since you use the sign bit of each number you are actually using 1 bit per number.  The fact that the bits are already allocated by Javascript is just a trick to make it appear as if you are using less memory.

I don't think you are being intentionally deceitful here, the concept of additional memory that seems to be embedded in the question is rather flawed.  O(n) memory is required just to store the array already unless you are using a stream so any algorithm that stores the entire list in memory at any point is truly O(n log n) anyway (log n because each number takes at most log n bits to store).

@WheatWizard Wouldn't it be O(n log m) since n (the number of inputs) and m (the largest integer) are independent of one another? Though I usually assume integers are a fixed width (more background in Java/C++/C than Python/Javascript) which means their storage is O(1)

@WheatWizard, I see your point. Like you said, the question wording is a bit open. However, I think this is a legitimate solution. No other solution makes any attempt to use fewer bits to store each number. The parameters were for O(1) additional space complexity and the array can only contain numbers between 1 and a.len.  It is worded like a homework question begging for such a solution. You are correct about O(n log n) initial space complexity if you assume that storage space per number is not fixed. This is seldom an assumption and I don't think it was implied in this competition.

C#, 65 67 bytes
With thanks to LiefdeWen for the 89 bytes base code here, here's an further shortened version of that
a=>{for(int p=0,q=0;;q++)for(p=0;p<q;)if(a[q]==a[p++])return a[q];}

We can dispense with the return -1 and length check as it's apparently OK to throw an exception if not found, so we just let the outer loop run off the end of the array. Some other whitespace changes, and jigging the declarations around to reduce the number of times we write "int" etc..

Pretty sure you can cut 1 char by making the second loop a while.
a=>{for(int p=0,q=0;;q++)while(p++<q)if(a[q]==a[p])return a[q];}

I checked, and it turns out, alas, it doesnt work out.. Doing p++<q means that although p is indeed incremented after the check of p<q, it is incremented before the inner loop code of if(a[p]==a[q]).. this has the undesirable effect of comparing a[1]==a[1] on the second iteration (q=1) which breaks the program. Still a useful comment though as it allowed me to chase down a bug (missing p=0 on inner loop), that unfortunately added 3 bytes but I was able to save 1 by moving p++ to the if, thanks to your suggestion

APL NARS 52 char 104 bytes
f←{1≠⍴⍴⍵:¯1⋄v←(⍵⍳⍵)-⍳⍴⍵⋄m←v⍳(v<0)/v⋄m≡⍬:¯1⋄(1⌷m)⌷⍵}

comments (for me f could return results even for vectors of characters that here seems to be the old strings)
1≠⍴⍴⍵:¯1     if ⍵ has rank different from 1 than it is not a vector so return -1
v←(⍵⍳⍵)-⍳⍴⍵   v is 0 0 0...0 only if there are not repetitions, else there is some value <0
m←v⍳(v<0)/v   m return the indices j of v where v[j]<0, and so ⍵[j] are all the duplicates
m≡⍬:¯1       if m is void than that index not exist, so no duplicate and return -1
(1⌷m)⌷⍵      else return the value in ⍵ of the first element of m

results
  f 1
¯1
  f 1,2,3,4
¯1
  f 1 2 3 3
3
  f 2 3 3 1 5 2
3
  f ,1
¯1

It's possible to use Dyalog's codepage to make it so it's 52 bytes. Also, you don't need to store the results in a function. And would either of these work in NARS? {1≠⍴⍴⍵:¯1⋄⍬≡m←v⍳v/⍨0>v←(⍵⍳⍵)-⍳⍴⍵:¯1⋄⍵⌷⍨1⌷m} or {1≠⍴⍴⍵:¯1⋄⍬≡m←v⍳(0>v)/v←(⍵⍳⍵)-⍳⍴⍵:¯1⋄(1⌷m)⌷⍵}?

@Zacharý I like "f←{1≠⍴⍴⍵:¯1⋄⍬≡m←v⍳(0>v)/v←(⍵⍳⍵)-⍳⍴⍵:¯1⋄(1⌷m)⌷⍵}" thank you; for what regard if the name of function I ' am not agree with community, for me the name has to be inside the solution, it will for me 2 characters more (or +4 bytes). It seems my target is not 100% codegolf, perhaps 80% . It would be better for a solution in APL count for codegolf it would be in characters and not in bytes

Python 3, 47 bytes
f=lambda l,i=0:l[i]if l[i]in l[:i]else f(l,i+1)

Try it online!

Add++, 69 bytes
D,k,@@*,BF€=B]ßEB*MVcGA$p
D,w,@@,BF€=s1<
D,l,@~,$
L~,AÞwB]dVbUG€k»lbU

Try it online!
How it works
Oddly enough, despite Add++ having a deduplicate command, this doesn't use it. This exits with an error code of 1 when there is no duplicated element.
We start by removing any elements without more than one occurrence, in order to leave the stack with an array containing the original array, preserving order, without any elements which only occur once. This is done by the use of filtering by the dyadic function w:
D,w,@@,BF€=s1<
L~,AÞw

Here, the lambda is implicitly called with the argument. The ~ tells it to unpack its argument to the stack beforehand, then the A pushes the argument to the stack. Thesefore, if the input looks like [a b c a c], the stack would look like
[a b c a c [a b c a c]]

We want this structure, called dyad-binding, due to the way the filter-keep quick, Þ, works in regard to non-monadic arguments. Here, its functional argument is w, a dyadic (two argument) function. This means that, instead of filtering over each element in the stack using w, it pops the top element of the stack, the list [a b c a c] in this case, and uses that as the right argument when filtering every other element.
So, for one iteration of w, the stack may look like this at the start of execution:
[[a b c a c] a]

Then BF flattens the stack, and then we come to another dyadic quick: €. Again, the popping behaviour is simulated, and a is used as the left argument to the succeeding function, the equality operator in this case. This compares a with the elements of [a b c a c], yielding an array of 1s and 0s. By now, the stack looks something like this
[1 0 0 1 0]

Finally, s takes the sum, and 1< asserts that it is greater than 1. This essentailly counts the occurences of each element of the input in the input itself, and removes them if the count is only 1 i.e. the element isn't duplicated at some point.
After applying Þw to the input, the stack results in
[a c a c]

We'll call this array A. The rest of the code is determining which of these remaining elements occurs for the second time first i.e. the actual task in the challenge.
Next, we want to perform k over the remaining list. In order to do this, with k being dyadic and taking A as its left argument. Again, we want to create the dyad-binding structure, but using the elements of A instead of the arguments. In a general case, if the stack looks like [a b c d e], where a - e are arbitrary pieces of data, the following code will convert that into a dyad-binding structure:
B]dVbUG

So, this makes our stack look like [a c a c [a c a c]], before calling k over €ach of the elements, using the array as the left argument.
D,k,@@*,BF€=B]ßEB*MVcGA$p

k is our main function to isolate the first deduplicated element. Here, we have our two arguments, I, the element in the array being iterated over, and A, our array containing the elements that occur more than once. The first part of the code, BF€=, identifies which elements of A are equal to I. Now, we generate the truthy indices - the indices of elements in A that are equal to I. There is a bug in ßE, causing it to start from 0 (corrected after the challenge was posted). However, as this means the first occurence if I will always be set to 0 because of this bug, and the offset of 1 doesn't change between elements, this means that we can avoid the lengthier dbLBc which is bug free. Let's use a as an example value for I. Now, our stack resembles
[[0 1] [1 0] [2 1] [3 0]]

The first element is the 0-based index i, the second whether or not I = A[i]. Next, we remove the indexes where I ≠ A[i], by taking the product of each pair with B*, then taking the maximum value with MVcG. Finally, we push I to the stack and pair them as a list. With I as a, the final value returned is:
[2 a]

This process happens over each element of A, eventually leading to a series of paired lists of the highest index of the element of A in A itself. Finally we want to find the element which has the lowest first element, the element whose duplcicate appears first. Here, as Add++ doesn't have a builtin to get the first or last element of a list, we use our third helper function l:
D,l,@~,$
L~,…»l…

While Add++ doesn't have a builtin for head of an array, it does have a minimum-by quick, ». We take the list which has the minimum return value when passed through the function l. This helper function unpacks its argument to the stack before performing any commands with the ~ command, then $ swaps them, so the index comes first and is the value returned. Essentially, we return the element with the smallest duplicated element.
Unfortunately, this returns the entire array, both the index and the element, rather than just the element, so we append a bU to unpack this array to the stack, returning only the last element of the pair - the first duplicated element.

C (gcc), 50 bytes
g;main(i){scanf("%d",&i);return i[&g]++?i:main();}

Try it online!
C (gcc), 51 bytes
g;main(i){for(;scanf("%d",&i),i[&g]^=1;);return i;}

Try it online!
C (gcc), 56 bytes
g;main(i){scanf("%d",&i);i[&g]++?printf("%d",i):main();}

Try it online!

Japt -æ, 5 bytes
VaWbU

Try it

Pip, 13 bytes
Tg@iNgHiUig@i

Takes the numbers as separate command-line arguments. Try it here! Or, here's a 15-byte equivalent in Pip Classic: Try it online!
Explanation
               g is list of cmdline args; i is 0 (implicit)
T              Loop till
 g@i           the i'th element of g (0-indexed)
    N          is in
     gHi       the first i elements of g:
        Ui      Increment i
          g@i  Return the i'th element of g

This outputs the first duplicate or, if there are no duplicates, the first number in the list (because the indexing wraps around).

TI-Basic, 32 bytes
Prompt A
Repeat 2=Ans(I
I+1→I
cumSum(ʟA=ʟA(I
End
ʟA(I

needs a fresh interpreter or I initialized to 0. Will error if there is no duplicates

JavaScript (Node.js), 29 bytes
x=>x.find(z=>(x[~z]+={})[25])

Try it online!
No effort on bonus at all
-1 from SuperStormer

29 bytes

Go, 97 bytes, \$O(n)\$ time, \$O(n)\$ space
func (l[]int)int{m:=make(map[int]int)
for i,e:=range l{if _,o:=m[e];o{return e}
m[e]=i}
return-1}

Attempt This Online!
Goes over the input slice exactly once per element. The map stores a pair per element, meaning \$O(n)\$ space as well.

C#, 48 bytes
x=>x.Where((_,i)=>x[..i].Contains(x[i])).First()

Try it online!
Alternative without LINQ, 58 bytes
x=>{for(int i=0;;)if(x[..++i].Contains(x[i]))return x[i];}

Try it online!

Arturo, 38 bytes
$->a[0-1select.n:1a=>[in?&take a<=1+]]

Try it!
$->a[              ; a function taking an arg a
    0-1            ; push -1
    select.n:1a=>[ ; select the first elt in a that
        in?&       ; is the current elt in
        <=1+       ; increment stack and duplicate
        take a     ; take that many of the first elts in a
    ]              ; end select
]                  ; end function


text:
How Fermat is this number?
Fermat numbers are positive integers that can be expressed as 22x+1 with an integer x.
Let us now define an attribute of a number called "Fermat-ness":

The Fermat-ness of the number is one less than the length of the chain of powers of two, starting from the base, with powers of two expanded so as to maximize the fermat-ness.
A number that is not a Fermat number has the Fermat-ness of zero.

So, 17 (=22220+1) has Fermat-ness three.
Challenge
Given a positive nonzero integer as input, output the Fermat-ness of the number.
Rules

You may take the input in binary, decimal, hexadecimal, as a bignum, or whatever format lets you golf best
Your solution must be able to process numbers with bit-lengths over 64 whichever representation you use.
Nonnegative integer powers only.
Standard loopholes are of course prohibited.
This is code-golf, so shortest answer wins.

Test cases
These are in format input->output. The input is in hexadecimal to save space.
10000000000000000000000000000000000000000000000000000000000000001 -> 2
1000000000000BC00000000000000000000000000000000001000000000000001 ->0
1234567890ABCDEF -> 0
100000000000000000000000000000001 -> 1
5 -> 2
11 -> 3
10001 -> 4
101 -> 1

The same in decimal:
115792089237316195423570985008687907853269984665640564039457584007913129639937 -> 2
115792089237316497527923305698859709742143344804209838213621568094470773145601 -> 0
1311768467294899695 -> 0
340282366920938463463374607431768211457 -> 1
5 ->2
17 -> 3
65537 -> 4
257 -> 1

Thanks to geokavel for invaluable input in the sandbox.

If I input 1111, how do you know it is in binary, decimal or hexadecimal???

@Jenny_mathy I meant for the answerer to decide what format of input they want.

@Mr.Xcoder It came up in the sandbox that there really aren't a lot of Fermat numbers of 64 bits or less. I'm claiming the question is intrinsically about bignums so I can demand bignum processing.

@HeikkiMäenpää Remember, no matter what others may recommend, the challenge is yours, and you can make it what you want.

Also, please take note I didn't downvote and Vote to close this challenge. I believe this is an interesting task and gave it an upvote. After you said why you added that spec, I believe it's totally justified. Great first challenge! (P.S.: thanks for adding the decimal test cases)

@Mr.Xcoder Noted. I appreciate you taking the time to point out issues with a newcomer's post.

What is the output for 1?

@LeakyNun 1 is not a Fermat number, so output is 0.

What about for 3?

If I use binary input, can it be an array of 0 and 1, or must it be a string?

@LuisMendo I think that would pass for a "bignum" format. I'm changing the rule to "whatever format".

@LeakyNun I think that'd be 1 (2**(2**0)+1).

Maybe you should write somewhere that you can only use integer powers. For example, 257 = 2^8 + 1 = 2^2^3 +1 (F-ness: 1). However, using non-integers, one could say it's 2^2^2^1.58496250072 (F-ness: 2). Technically, with non-integers I think you could get scores of infinity.

I think it's too early too accept. Usually wait 1 or 2 weeks. Some say to never accept!

Jelly, 15 14 bytes
1 byte thanks to Jonathan Allan.
’µBḊ⁸LṀ?µÐĿḊḊL

Try it online!

Save a byte with: BḊCL⁸Ạ? -> BḊ⁸LṀ?

Python 2, 103 81 bytes
n=input()-1
i=l=0
while 2**2**i<=n:
 if n==2**2**i:n=2**i;i=-1;l+=1
 i+=1
print l

Try it online!
I realized not being stupid would help lower my byte count, so I did that.  Also exponentiation as opposed to logarithms.

Perl 6, 62 bytes
{my@a=first :kv,*>=0,(^∞).map(2**2** *+1-$_);++@a[0]*!@a[1]}

Try it online!

RProgN 2, 75 bytes
«\`n=1\]{1-\n*\]}:[»`^=«1-`n=001{]2\^2\^ne{2\^`n=1+0}{1+}?]2\^2\^n>¬}:[»`¤=

Try it online!
It's only 70 bytes if you don't add the «»'¤= which assigns the Fermatness calculation to the ¤ character.  If you do that, you'll need to put the number in the Header section of TIO instead of in the Footer like it is now.
This effectively uses the same logic as my Python answer, so if you don't care about how RProgN 2 works, just look at that one for an explanation of what's going on.  Otherwise
Code breakdown:
«\`n=1\]{1-\n*\]}:[»`^=
«                  »`^=`                            # Create a local function and assign it to the ^ character (x y ^ is x to the power of y)
 \`n=                                               # Swap the top two values of the stack and assign the new top to the variable n
     1\]                                            # Push a 1 (our starting point for x to the y), swap with the y value, then duplicate y
        {       }:                                  # Start a while loop that pops the top stack value and loops if it is truthy
         1-                                         # Subtract 1 from y to keep a tally of how many multiplications we've done
           \n*                                      # Swap the counter with our current value and multiply it by n
              \]                                    # Swap this new value with the current value of y, and duplicate it to be used as the truthy value for the loop

«1-`n=001{]2\^2\^ne{2\^`n=1+0}{1+}?]2\^2\^n>¬}:[»`¤=# The main Fermatness function (x ¤ to get the Fermatness of x)
«                                               »`¤=# Create another local function for this calculation
 1-`n=                                              # Decrement the input by 1 and assign it to n
      001                                           # Push a counter for Fermatness, a counter for calculating 2^2^i, and an initial truthy value
         {                                   }:     # Start a while loop for calculating the Fermatness
          ]2\^2\^ne                                 # Duplicate i, calculate 2^2^i, and compare it to n
                   {         }{  }?                 # Start an if statement based on the equality of 2^2^i and n
                    2\^`n=                          # n==2^2^i, so set n to 2^i (same as saying n=log_2(n))
                          1+0                       # Increment the Fermatness counter and reset i
                               1+                   # n!=2^2^i, so just increment i
                                   ]2\^2\^n>¬       # Duplicate the counter and check if 2^2^i<=n, if true the loop continues, else it exits
                                               [    # Pop i from the stack, leaving us with just the Fermatness counter

Unfortunately the log function Š and the normal exponentiation function ^ lack the precision to do this natively, so I had to redefine how exponentiation worked since multiplication carries much more precision.  Without that redefine, this answer would be 23 bytes shorter.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Square a Number my Way
People keep telling me that the square of a number is the number multiplied by itself.  This is obviously false.  The correct way to square a number is to make it into a square, by stacking it on top of itself a number of times equal to the number of digits it has, and then reading all the numbers from the resultant square, both horizontally (from left to right only) and vertically (from up to down only), and then adding them together.  So, for the number 123, you first create the square:
123
123
123

Then you take all of the rows and columns from the square, and add them together:
123+123+123+111+222+333

Which gives us a result of 1035.
For negative numbers, you stack normally (remember that you only count the number of digits, so the negative sign is not included in the length), and then read the horizontal numbers normally (with negative signs), and then ignore the negative signs for the vertical numbers.  So, for the number -144 we get the square:
-144
-144
-144

Which gives us -144-144-144+111+444+444, which equals 567
For numbers with only one digit, the square is always equal to the number doubled (read once horizontally and once vertically).  So 4 gives us
4

Which gives us 4+4, which equals 8.
For numbers with decimal parts, stack normally (remember that only digits are counted in the number of times you stack the number, and therefore the decimal point is not counted), and ignore the decimal symbols when reading the vertical numbers.  For example, the number 244.2 gives us
244.2
244.2
244.2
244.2

Which gives us 244.2+244.2+244.2+244.2+2222+4444+4444+2222, which equals 14308.8.
Fractional or complex numbers cannot be squared.
Your Task:
I'm tired of squaring numbers my way by hand, so I've decided to automate the process.  Write me a program or function that takes a float or string, whichever you prefer, as input and returns the result of squaring it my way.
Examples:
123    -> 1035
388    -> 3273
9999   -> 79992
0      -> 0
8      -> 16
-6     -> 0
-25    -> 27
-144   -> 567
123.45 -> 167282.25
244.2  -> 14308.8
2      -> 4
-0.45  -> 997.65
0.45   -> 1000.35

Scoring:
My hands are getting cramped from writing out all those squares, and my computer doesn't support copy/paste, so the entry with the least amount of code for me to type (measured in bytes for some reason?) wins!

"123.45" and "244.2" aren't valid floats in and of itself because the computer stores number in binary. This isn't normally a problem until the problem relies on the decimal representation.

@LeakyNun, I don't really know what you mean by that.  The problem isn't unsolvable (at least in python), I'm pretty sure I could do it fairly easily, although in a large number of bytes.  It would require some string manipulation, however.

@Gryphon So we must take input as a string?

No, but to solve this problem, you will probably have to convert the number to a string.

@Gryphon This is where it fails. 244.2 is not a float number. It cannot be converted to the string "244.2".

@LeakyNun, in python 2.7, my_float = 244.2 print "My float is "+str(my_float)  seems to work just fine

The space between "244.2" and "print" is supposed to be a newline.

@Gryphon But behaviours like this makes it very inconvenient.

05AB1E, 7 bytes
þSDg×+O

Try it online!
Explanation
þSDg×+O Implicit input
þ       Keep digits
 S      Get chars
  D     Duplicate
   g    Length
    ×   Repeat string(s)
     +  Add (implicit input added to all elements)
      O Sum

Ooo explanation when you can  please

Also I would note that the single leading zero is a requirement on the input for -1 < input < 1 (i.e. 0.45 and .45 are different inputs but the same number, only the former is acceptable)

@JonathanAllan The latter isn't handled anyways.

@JonathanAllan Done.

Jelly,  13  12 bytes
fØDẋ€L$ŒV+VS

A monadic link accepting a list of characters (a well-formed decimal number, the single leading zero being a requirement for -1 < n < 1) and returning a number.
Try it online!
14 bytes to accept and return numbers (input limited at +/-10-5 by ŒṘ): ŒṘfØDẋ€L$ŒV+⁸S.
How?
fØDẋ€L$ŒV+VS - Link: list of characters         e.g. "-0.45"
 ØD          - yield digit characters                "0123456789"
f            - filter keep                           "045"
      $      - last two links as a monad:
     L       -   length (number of digit characters) 3
   ẋ€        -   repeat list for €ach digit          ["000","444","555"]
       ŒV    - evaluate as Python code (vectorises)  [0,444,555]
          V  - evaluate (the input) as Jelly code    -0.45
         +   - addition (vectorises)                 [-0.45,443.55,554.55]
           S - sum                                   997.65

Umm, you can replace +€ with + in 15-byte version for -1.

Already did, thanks though!

Umm not in the 15-byte version. EDIT: 3 seconds too early I suppose...

Yup just noticed you said 15 byte version - thanks again!

Haskell, 59 56 bytes
f s|l<-filter(>'.')s=0.0+sum(read<$>(s<$l)++[c<$l|c<-l])

The input is taken as a string.
Try it online!
How it works
l<-filter(>'.')s      -- let l be the string of all the numbers of the input string
f s   = 0.0 + sum     -- the result is the sum of (add 0.0 to fix the type to float)
   read<$>            -- turn every string of the following list into a number
   s<$l               -- length of l times the input string followed by
   [c<$l|c<-l]        -- length of l times c for each c in l

Japt v2, 16 bytes
o\d
l
¬xpV +V*Ng

Test it online!
Explanation
o\d    First line: Set U to the result.
o      Keep only the chars in the input that are
 \d      digits. (literally /\d/g)

l    Second line: Set V to the result.
l    U.length

¬xpV +V*Ng    Last line: implicitly output the result.
¬             Split U into chars.
 x            Sum after
  pV            repeating each V times.
     +V*Ng    Add V * first input (the sum of the horizontals) to the result.

C# (.NET Core), 150 141 133 bytes
Saved 9 bytes thanks to @TheLethalCoder
Saved another 8 bytes thanks to @TheLethalCoder
a=>{var c=(a+"").Replace(".","").Replace("-","");int i=0,l=c.Length;var r=a*l;for(;i<l;)r+=int.Parse(new string(c[i++],l));return r;}

Try it online!
Takes a string as an input and outputs the 'squared' number as a float.

This code follows the following algorithm:

Create a new string from the input, but without the decimal points and symbols, so we can get our length and the numbers for the columns from there.

Calculate the input times the length of the string we created at point 1.

For each column in our 'square', create a new string with the column number and the row length and add it to our result.

Example:
Input: -135.5

If we replace decimal points and symbols we get the string 1355, which has a length of 4.
The input times 4: -135.5 * 4 = -542.
Now we create new strings for each column, parse them and add them to our result:
1111, 3333, 5555, 5555.

If we sum these numbers up we get 15012, which is exactly what our program will output.

Welcome on the site, and nice first answer (the explanations in particular are appreciated!) !

@Dada Thank you! Even tough I am rather unpleased by the bytes I gained from stuff like string.Replace(), but I guess thats the only way it works!

Might be able to save some bytes by setting i and l to floats.

@TheLethalCoder Thought of that aswell, sadly indexing does not work with floats, and .Length cannot implicitly be converted to float.

a=>{var c=a.Replace(".","").Replace("-","");int i=0,l=c.Length;var r=float.Parse(a)*l;for(;i<l;)r+=int.Parse(new string(c[i++],l));return r;} 141 bytes. Might be able to save by taking input as a float and casting to a string with n+"" but I haven't checked.

Nice first answer though! Check some tips for C# golfing here.

@TheLethalCoder Taking input as float really did save some more, thanks!

JavaScript, 75 62 bytes
a=>(b=a.match(/\d/g)).map(b=>a+=+b.repeat(c),a*=c=b.length)&&a

Try it online
-2 bytes thanks to Arnauld
-5 bytes thanks to Shaggy (I though the function must receive a number, but now I see that lot of other answers receive string too)

Python 3, 95 94 87 85 84 bytes
def f(i):l=[x for x in i if"/"<x];k=len(l);print(k*float(i)+sum(int(x*k)for x in l))

Test Suite.
Python 3, 78 bytes
lambda x:sum(float(i*len(z))for z in[[i for i in str(x)if"/"<i]]for i in[x]+z)

Test Suite.
The second approach is a port to Python 3 inspired by @officialaimm's solution.

Python 2, 81 74 bytes
-7 bytes thanks to @Mr. Xcoder: '/'<i

Takes in integer or float, returns float.

lambda x:sum(float(i*len(z))for z in[[i for i in`x`if"/"<i]]for i in[x]+z)

Try it online!
Explanation:
Say 123.45 is given as input. [i for i in`x`if"/"<x] gives a list of stringified integers ['1','2','3','4','5'] (which is also z). Now we iterate through [x]+z i.e. [123.45,'1','2','3','4','5'], multiplying each element by len(z), here 5 and converting each to a Float (so that strings also convert accordingly), yielding [617.25,11111.0,22222.0,33333.0,44444.0,55555.0]. Finally we calculate the sum(...) and obtain 167282.25.

78 bytes. Replace i.isdigit() with "/"<i<":"

74 bytes. You can replace i.isdigit() with "/"<i, in fact, because both . and - have lower ASCII codes than digits, adn / is in between them

You're welcome. I've ported it to Python 3 as an alternative to my answer

Brachylog, 23 bytes
{∋ịṫ}ᶠ⟨≡zl⟩j₎ᵐ;[?]zcịᵐ+

Try it online!
Brachylog doesn't go well with floats...
Explanation:
{∋ịṫ}ᶠ⟨≡zl⟩j₎ᵐ;[?]zcịᵐ+ Takes string (quoted) input, with '-' for the negative sign
     ᶠ                  Return all outputs (digit filter)
{   }                    Predicate (is digit?)
 ∋                        An element of ? (input)
  ị                       Convert to number (fails if '-' or '.')
   ṫ                      Convert back to string (needed later on)
      ⟨   ⟩             Fork
       ≡                 Identity
         l               Length
                        with
        z                Zip
             ᵐ          Map
            ₎            Subscript (optional argument)
           j              Juxtapose (repeat) (this is where we need strings)
              ;         Pair with literal
               [ ]       List
                ?         ?
                  z     Zip
                   c    Concatenate (concatenate elements)
                     ᵐ  Map
                    ị    Convert to number
                      + Add (sum elements)

Husk, 15 bytes
§+ȯṁrfΛ±TṁrSR#±

Takes a string and returns a number.
Try it online!
Explanation
It's a bit annoying that the built-in parsing function r gives parse errors on invalid inputs instead of returning a default value, which means that I have to explicitly filter out the columns that consist of non-digits.
If it returned 0 on malformed inputs, I could drop fΛ± and save 3 bytes.
§+ȯṁrfΛ±TṁrSR#±  Implicit input, e.g. "-23"
             #±  Count of digits: 2
           SR    Repeat that many times: ["-23","-23"]
         ṁr      Read each row (parse as number) and take sum of results: -46
  ȯṁrfΛ±T        This part is also applied to the result of SR.
        T        Transpose: ["--","22","33"]
     fΛ±         Keep the rows that contain only digits: ["22","33"]
   ṁr            Parse each row as number and take sum: 55
§+               Add the two sums: 9

Perl 5, 37 33 + 1 (-p) = 38 34 bytes
$_*=@n=/\d/g;for$\(@n){$_+=$\x@n}

Try it online!
Used some tricks from Dom's code to shave 4 bytes
Explained:
@n=/\d/g;    # extract digits from input
$_*=@n;      # multiply input by number of digits
for$\(@n){   # for each digit:
  $_+=       # add to the input
  $\x@n}     # this digit, repeated as many times as there were digits
             # taking advantage of Perl's ability to switch between strings
             # and numbers at any point

Came up with a very similar approach, but managed to get a couple of bytes off using $\ and exiting the loop: try it online!

Used some inspiration from you to shave mine down.  What's the "}{" construct at the end of yours?  I'm not familiar with that one.

It's one I learnt from this site, basically -n and -p literally wrap a while(){...} around the code so }{ breaks out of that. This unsets $_ but if you use $\  as your variable it'll still get printed since $\  is appended to every print. Means you can stores number or something in that and disregard $_. Not sure that was a great explanation, but check out the Tips for golfing g in Perl thread, I'm sure that'll explain it better! Glad to have helped your score though!

Jelly, 17 bytes
ŒṘfØDẋ€L©$ŒV;ẋ®$S

Try it online!

Pyth, 18 bytes
s+RvQsM*RF_lB@jkUT

Try it here.

Pyth, 21 20 bytes
K@jkUTQ+smv*lKdK*lKv

Test suite.
Uses a completely different approach from @EriktheOutgolfer's answer, which helped me golf 1 byte in chat, from 22 to 21.

Explanation

K@jkUTQ+s.ev*lKbK*lKv

K@jkUTQ                   - Filters the digits and assigns them to a variable K.
         m                - Map. Iterated through the digits with a variable d
           v              - Evaluate (convert to float).
            *lKd          - Multiplies each String digit by the length of K.
        s                 - Sum
       +                  - Sum
                 *lKvQ    - Multipies the number  by the length of the digits String

Octave, 100 82 bytes
Thanks a lot @TomCarpenter for teaching me that assignments have a return value and saving me 18 bytes!
@(v)(n=nnz(s=strrep(num2str(abs(v)),'.','')-'0'))*v+sum(sum(s'*logspace(0,n-1,n)))

Try it online!
Ungolfed/Explanation
function f=g(v)
  s=strrep(num2str(abs(v)),'.','')-'0';  % number to vector of digits (ignore . and -)
  n=nnz(s);                              % length of that vector
  f=n*v+sum(sum(s'*logspace(0,n-1,n)))   % add the number n times and sum the columns of the square
end

The way this works is that we basically need to add the number itself n times and then add the sum of the columns. Summing s' * logspace(0,n-1,n) achieves the sum of columns, for example if v=-123.4 that matrix will be:
[ 1     10    100   1000;
  2     20    200   2000;
  3     30    300   3000;
  4     40    400   4000 ]

So we just need to sum it up and we're done.

You can save 18 bytes by smushing it all into an anonymous function @(v)(n=nnz(s=strrep(num2str(abs(v)),'.','')-'0'))*v+sum(sum(s'*logspace(0,n-1,n))). Try it online!

PHP, 78 88 +1 bytes
for($e=preg_match_all("#\d#",$n=$argn);~$c=$n[$i++];)$s+=str_repeat($c,$e);echo$s+$n*$e;

Run as pipe with -nR.
May yield warnings in PHP 7.1. Repace $c,$e with $c>0?$c:0,$e to fix.

Swift 4, 139 134 bytes
func f(s:String){let k=s.filter{"/"<$0};print(Float(s)!*Float(k.count)+k.map{Float(String(repeating:$0,count:k.count))!}.reduce(0,+))}

Test Suite.

Explanation

func f(s:String) - Defines a function f with an explicit String parameter s.

let k=s.filter{"/"<$0} - Filters the digits: I noticed that both - and . have smaller ASCII-values than all the digits, and / is between ., - and 0. Hence, I just checked if "/" is smaller than the current character, as I did in my Python answer.

print(...) - Prints the result.

Float(s)!*Float(k.count) - Converts both the String and the number of digits to Float and multiplies them (Swift does not allow Float and Int multiplication :()). So it adds the number x times, where x is the number of digits it contains.

k.map{Int(String(repeating:$0,count:k.count))! - k.map{} maps over k with the current value $0. String(repeating:$0,count:k.count) takes each digit, creates a String of x identical digits and Float(...)! converts it to a Floating-point number.

.reduce(0,+) - Gets the sum of the list above.

And finally + sums the two results.

Let's take an example!
Say our String is "0.45". First off, we filter the digits, so we are left with 0, 4, 5. We convert "0.45" to Float and multiply by the number of digits: 0.45 * 3 = 1.35. Then we take each digit and turn it into a String repeating that digit until it fills the width of the square (how many digits there are): 0, 4, 5 -> 000, 444, 555. We sum this, 000 + 444 + 555 = 999. Then we just add the results together: 1.35 + 999 = 1000.35.

C#, 139 137 bytes
using System.Linq;n=>{var d=(n+"").Where(char.IsDigit);return d.Sum(i=>int.Parse(new string(i,d.Count())))+new int[d.Count()].Sum(_=>n);}

Saved 2 bytes thanks to @Ian H.
Try it online!
Full/Formatted version:
namespace System.Linq
{
    class P
    {
        static void Main()
        {
            Func<double, double> f = n =>
            {
                var d = (n + "").Where(char.IsDigit);
                return d.Sum(i => int.Parse(new string(i, d.Count()))) + new int[d.Count()].Sum(_ => n);
            };

            Console.WriteLine(f(123));
            Console.WriteLine(f(-144));
            Console.WriteLine(f(4));
            Console.WriteLine(f(244.2));

            Console.ReadLine();
        }
    }
}

You can save 2 bytes at the beginning by using var d=(n+ ... instead of var d = (n ....

@IanH. Forgot to remove all the spaces -_- That's what I get for answering whilst doing a support call.

Mathematica, 107 bytes
(t=Length[s=#&@@RealDigits[#]//.{a___, 0}:>{a}];If[IntegerPart@#==0,t++];t#+Tr[FromDigits@Table[#,t]&/@s])&

Python 3, 68 70 73 77 bytes
lambda n:sum(float(n)+int(_*sum(x>"/"for x in n))for _ in n if"/"<_)

Try it online!
Loops over every digit character and repeats it by the number of digit characters overall, makes that into an integer, and adds that to n. This way n gets added d times, the horizontal part of the sum, along with the digit repetition, which is the vertical part. Originally used str.isdigit but >"/", thanks to others in this thread, saved a lot of bytes. Saves two bytes by taking n as a string, but the output is messier.
lambda n:sum(n+int(_*sum(x>"/"for x in str(n)))for _ in str(n)if"/"<_)

Try it online!

Japt v2.0a0 -x, 10 bytes
Takes input as a string.
f\d çU
cUy

Try it or run all test cases
f\d çU\ncUy     :Implicit input of string U                    > "-0.45"
f               :Match (returns an array)
 \d             :  RegEx /\d/g                                 > ["0","4","5"]
    çU          :Fill with U                                   > ["-0.45","-0.45","-0.45"]
      \n        :Reassign to U
        c       :Concatenate
         Uy     :  U transposed                                > ["-0.45","-0.45","-0.45","---","000","...","444","555"]
                :Implicit output of sum of resulting array     > 997.65

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Weakened Binary Walls
Inspired by Create a binary wall
Given a list of positive integers, we can write them out all above each other like so, for [2, 6, 9, 4] as an example:
0010
0110
1001
0100

We can imagine this as a wall:
..#.
.##.
#..#
.#..

However, this is a very weak wall, and it has collapsed! Each 1 (#) falls down until it hits the "ground" or another 1 (#). The 0s (.s) are present in spots left by moved 1s.
This becomes the following:
....
....
.##.
####

Which translates back to:
0000
0000
0110
1111

Which, as a list of numbers, is [0, 0, 6, 15].
Another test case
[10, 17, 19, 23]

This becomes:
01010
10001
10011
10111

which becomes:
00000
10011
10011
11111

translating back to:
[0, 19, 19, 31]

Challenge
Given a list of positive integers, apply this transformation to the list. Input/Output as lists of positive integers in any reasonable format. Standard loopholes apply.
This is a code-golf, so the shortest answer in bytes wins!

Sandbox Post

More testcases? You know, non-square testcases would be good.

@LeakyNun Sure. I'll do that.

That's just a sorting problem for bit arrays.

@MarcusMüller You're right - I realized that after the MATL answer :P

@TheLethalCoder :) It was a nice challenge :)

MATL, 4 bytes
BSXB

Try it at MATL Online
Explanation
    % Implicitly grab input as an array
    %   STACK: [10, 17, 19, 23]
B   % Convert each element to binary where each decimal number results in a row
    %   STACK: [0 1 0 1 0;
    %           1 0 0 0 1;
    %           1 0 0 1 1;
    %           1 0 1 1 1]
S   % Sort each column, placing all of the 1's at the bottom of each column
    %   STACK: [0 0 0 0 0;
    %           1 0 0 1 1;
    %           1 0 0 1 1;
    %           1 1 1 1 1]
XB  % Convert each row from its binary representation to its decimal number
    %   STACK: [0, 19, 19, 31]
    % Implicitly display the result

o_O How does this work :o

Did MATL just out-golf Jelly by 4 bytes? o_O

5 bytes now :-p

I never thought there'd be a built-in to move the ones to the bottom xD +1

@HyperNeutrino I basically also used sort on my answer

@totallyhuman well, wait till Dennis comes

@LeakyNun The thing is, well, you had to use zip.

@JungHwanMin I have tried this in Jelly too, I don't think it's really possible under 9 bytes...

Python, 68 bytes
f=lambda a:a and[x|y&a[0]for x,y in zip([0]+f(a[1:]),f(a[1:])+[-1])]

Try it online!

JavaScript (ES6), 50 bytes
f=a=>a.map(_=>a.map((e,i)=>a[a[i]|=a[--i],i]&=e))&&a

Explanation: Suppose two rows of the wall were like this:
0011
0101

The result needs to be this:
0001
0111

In other words, the first row becomes the AND of the two rows and the second row becomes the OR of the two rows. This just needs to be repeated enough times for all the bits to fall to the bottom.

Python 3.5, 60 bytes
def f(a,*t):
 if t:b,*r=f(*t);t=f(a|b,*r);a&=b
 return(a,*t)

Try it online!
Takes input like f(2, 6, 9, 4). Assumes input is non-empty. Uses a lot of tuple unpacking.

Jelly, 9 bytes
BUz0Ṣ€ZUḄ

Try it online!

Japt, 16 bytes
m¤z3 ®¬n qÃz mn2

Try it online! using the -Q flag to format the array result.
Explanation
m¤z3 ®¬n qÃz mn2    Implicit: U = input array.
                        [10, 17, 19, 23]
m¤z3                Map U to binary strings and rotate the array left 90°
                         1010       0111
                        10001   ->  1011
                        10011       0001
                        10111       1000
                                     111
®¬n qÃ              Sort each binary string, putting 0s and spaces at the start
                        0111
                        0111
                        0001
                        0001
                         111
z mn2               Rotate right 90° and convert each back to a number
                         0000       0
                        10011   ->  19
                        10011       19
                        11111       31
                    Implicit output of resulting array

I think you can save a byte with mì2 z3 mn z mì2

@ETHproductions It seems rotating the 2D array, instead of rotating the array of strings, pads each inner array with null instead of spaces. So that doesn't seem to work. And null is sorted to the right of the 1s, unlike spaces, which are sorted to the left.

Octave, 29 25 bytes
4 bytes saved thanks to @Stewie
@(x)bi2de(sort(de2bi(x)))

de2bi/bi2de saves 4 bytes in octave. Works on octave-online.net.

@StewieGriffin Thanks!

Mathematica, 64 bytes
#~FromDigits~2&/@(Sort/@(PadLeft[#~IntegerDigits~2&/@#]))&

 is \[Transpose]
This converts the input (a list of numbers) to a list of lists of digits, pads it to be a square matrix, transposes it, sorts the rows so the 1's "fall" to the bottom, transposes back, then converts back into numbers.

05AB1E, 9 bytes
bí0ζR€{øC

Try it online!
Kinda different algorithm from Magic's.

ζ, damnit. Deleted mine, take my +1.

@MagicOctopusUrn Why did you delete yours? No need to.

It's not really much different (in terms of algorithm) and this was 25% better.

Dyalog APL (23 characters)
{2⊥¨↓⍉↑{⍵[⍋⍵]}¨↓2⊥⍣¯1⊢⍵}

Convert the input arguments into a binary matrix
Split the matrix into columns
Sort the columns into ascending order
Convert the sorted rows back into decimal

Example
  {2⊥¨↓⍉↑{⍵[⍋⍵]}¨↓2⊥⍣¯1⊢⍵}10 17 19 23
      0 19 19 31

Thanks to Zacharý for correcting me on this one.

You can replace with (⊥⍣¯1)⍵ with ⊥⍣¯1⊢⍵. Also, I don't think you need the axis specification on split (↓[1]=>↓).

Oh, and you're supposed to convert it back to a list!

This is invalid.

Thank you, Zacharý, I was working on this late last night and I think I misread the problem. I've modified my solution now.

Well, good job! (⊥⍣¯1 really needs to be a builtin). And thank you for actually getting my username right.

Dyalog APL, 24 21 19 bytes
2⊥↑{⍵[⍋⍵]}¨↓2⊥⍣¯1⊢⎕

Try it online! (modified so TryAPL accepts it as valid)
How?

⎕ evaluated input (arrays are space separated)
2⊥⍣¯1⊢ converts each each of the arguments to binary (transposed of what is in the question)
↓ turns a 2D array into a vector of vectors
{⍵[⍋⍵]}¨ sorts each of the elements of the vector
↑ turns the vector of vectors into a 2D array again
2⊥ convert from binary (since it sort of transposes it, we arrive at the correct result)

J, 13 bytes
/:~"1&.|:&.#:

Try it online!
Explanation
/:~"1&.|:&.#:  Input: array M
           #:  Convert each in M to binary with left-padding
       |:&     Transpose
/:~"1&         Sort each row
     &.|:      Inverse of transpose (which is just transpose)
         &.#:  Inverse of converting to binary

There's that binary left-padding again, +1. And also, can you explain why you would need to use the inverse of transpose, since it is just transpose?

@Zacharý The inverses are used to undo the operations used before sorting each row. It's true that the inverse of transpose is just transpose, but another way to see this is as <convert from binary> <transpose> <sort each row> <transpose> <convert to binary> M, where the first two functions are just the inverses of the last two.

JavaScript, 127 125 bytes
a=>a[m='map'](_=>b[m]((n,i)=>n&&(b[i]--,d|=1<<i),d=0)&&d,b=[...Array(32)][m]((_,c)=>a[m](e=>d+=!!(2**c&e),d=0)&&d)).reverse()

Try it online
-2 bytes thanks to Cows quack

(1<<c)&e can become 2**c&e

Python 2, 142 bytes
... and still golfing... hopefully –– Any help appreciated!
def c(l):b=[bin(n)[2:]for n in l];print[int(n,2)for n in map(''.join,zip(*map(sorted,zip(*['0'*(len(max(b,key=len))-len(x))+x for x in b]))))]

A big chunk of this is for padding the numbers with zeroes.
More readable:
def collapse(nums):
    bins = [bin(n)[2:] for n in nums]
    bins = [('0'*(len(max(bins, key = len)) - len(x))) + x for x in bins]
    print [int(n, 2) for n in map(''.join, zip(*map(sorted, zip(*bins))))]

This creates an array of the binary string representations, pads it, rotates it 90º clockwise, sorts each row, rotates it back 90º, and then creates integers out of each row.

142 bytes, you have some redundant parenthesis.

@Mr.Xcoder , oh yes that was silly

Japt, 9 bytes
m¤ù yñ mÍ

Try it
m¤ù yñ mÍ     :Implicit input of array
m             :Map
 ¤            :  To binary strings
  ù           :Left pad each with spaces to the length of the longest
    y         :Transpose
     ñ        :Sort each and transpose back
       m      :Map
        Í     :  To decimal

Husk, 11 bytes
mḋTmOT0mo↔ḋ

Try it online!


text:
Determine max speed horse can run without passing or slowing
Story
There is a woman, named Sarah, whom likes smooth horse rides.  She's going to go for a ride down a path too thin to pass any other horses she may come across - and so that her ride can be as smooth as possible she does not want to have to change speed though she would prefer to get to her destination as fast as possible.
Situational Definition
There is a random number of horses traveling at a random speed which are at a random point between the start and end of the path when the Sarah departs.  You must calculate the fastest speed at which she can travel without reaching another of the horses have having to slow her speed.
All horses on this path will slow to the speed of the horse in front of it if it reaches that horses position.  It's a popular trail, and there is always at least 1 horse.
Example "starting" point graphic:

Example "half way" graphic:

Primary Success Criteria
Each post must have a code golf answer - in which you try to solve the problem in as few characters as possible.
I'm open to changes on these policies but I thought it would be interesting if I were allowed to have the following special rules: (If they are deemed unfair or flawed I'll certainly reconsider)

Line endings are assumed to be '\n' not '\r\n' and are only counted as 1 character.  This may allow slightly more readable code in some languages.
To encourage answering in languages that would not usually be "winners" in code golf I'd like to institute a point modification system:

Code golf languages have their character count multiplied by 1.25. (I will consider any language in which at least 80% of it's operators or keywords are 1 or 2 characters to be a code golf language.)
Answers using compiled strictly typed languages (C, Java, etc) can have their character count multiplied by 0.85 (Because usually it requires more characters to code things in those languages.) Languages like Javascript that may be "compiled" by something like V8 do not count and are loosely typed.

(These may be modifiers may be altered or changed slightly if they are unfair or need improvement)
Implementation technical details
You are not required to post surrounding code that is not specific to this problem and is required by your language for your code to execute.  For example, in java your code would need a "class" and a main function to execute; however, you can simply provide code as if it were within the "main" function.  Any import statements for standard libraries that are required for your code to run should be provided in a code block below your main code, and these will not count towards your character count.  You shouldn't use any libraries someone who can compile or execute that language wouldn't have out of the box.
Code Scope
Your code should work assuming that variables "d" and "h" (or a closest variant in your language if for some reason those are not acceptable) are present in your scope.
"d" is a number with decimal precision (ex. double/float) representing the distance to the destination from 0.
"h" is an array or list of some structure that can support two values "p" and "s" which are also decimals.
Testing code
You should provide a some lines for testing in a code block below your answer code block that assigns d to a random value between or equal to 200 and 1000, and "h" to a list of length between or equal to 10 and 40 in which each list item stores a value for position between 0 and the value of d, and speed is between or equal to 5 and 10. (Not Sarah's horse is the worlds fastest horse and can travel as fast as is optimal, even if that speed greatly exceeds 10)
Results
Your answer should store the speed Sarah should travel in a variable capable of storing decimal values such that it could be used in lines below your code for any purpose including answer checking, logging to a console, or outputting in the programs UI.  This variable should be named "o" if possible which is short for "optimal speed".
To recap your answer should:

Have a code block which outputs the speed assuming "d" and "h" are present in the scope.
Have a code block below which assigns "d" and "h" to appropriate values for distance and a list of horses.
Output the correct value for "o" which is the speed to travel.
(Again if these variable names are not acceptable in your language please just note why and what variable names you used in place of the ones provided)

The answer with the shortest character count wins.
Example situation:
"d" is 250, and "h" has one item with "p" of 50 and speed of "20".  In this simple case Sarah can travel at 250/((250-50)/20)=25. So "o" should be 25 in this case.
You should be-able to handle cases in which there are numerous horses slowing after reaching the horse(s) in front of them.
Secondary Objective
If your answer is written in JavaScript and works with the data provided or you provide an additional conforming JavaScript answer in the same post, I will execute your code in something like this in a web page I will later create in the latest version of the chrome browser:
var horse = (pos, speed) => ({pos: pos, speed: speed})
var rhorse = (d) => horse(rand(d), rand(5)+1)

var rand = (i) => Math.random()*i
var irand = (i) => Math.round(Math.random()*i)

var answers = []

answers.push(function(d, h){
    //YOUR CODE
})

function checkAnswer(ans, d, h){
    // Code that which is proven to answer the question reliably
}
var speeds = []
for (var a = 0; a < answers.length; a++) {
    var totalTime = 0
    for (var i = 0; i < 1000; i++) {
        var d = rand(800)+200
        var numhorses = irand(30)+10
        var h = []

        for (var i = 0; i < numhorses; i++)
            horses.push(rhorse(d))

        var start = performance.now()

        answers[a]()

        totalTime += performance.now()-start

        if (!checkAnswer(ans)
    }
    var time = (totalTime/1000)
    speeds.push({time: time, answer: a})
    console.log("Answer " + a + " completed with an average speed of " + time)
}

//Todo: sort by time

console.log(speeds)

And then the times I got for each answer will be posted.  This does not determine the winner or the question I will mark as the "answer".  It is merely another metric that is being measured. (And if you have interest in trying to out-perform other code examples you can compete that way as well).  As mentioned you may provide a second code blog to be used to for the performance comparison.
Example answer (That would fail)
"
62 Characters
someHorse = h[0]
o = (d-someHorse.p)/someHorse.s
o = d/o

Test code:
var horse = (p, s) => ({p: p, s: s})
var rhorse = (d) => horse(rand(d), rand(5)+1)

var rand = (i) => Math.random()*i
var irand = (i) => Math.round(Math.random()*i)
var d = rand(800)+200
var numhorses = irand(30)+10
var h = []

for (var i = 0; i < numhorses; i++)
    horses.push(rhorse(d))

"
You can just note you'll use my test code here if you're code is written in javascript.
Results:

ppperry (By the way, where is he?)- 31 characters

Disclaimer
This is my first code golf question.  I'm willing to fix flaws, please go easy with me.
This question was very strongly inspired by: https://code.google.com/codejam/contest/8294486/dashboard

Let us continue this discussion in chat.

APL (Dyalog Classic), 10 9 bytes
⌊/s÷1-p÷d

Taking s, p and d as per the specs, respectively horse speeds, positions and the total distance to be travelled.
Explanation:
      p÷d  ⍝ Divide each horse position by the total distance
    1-     ⍝ and do 1 minus that.
  s÷       ⍝ Divide each speed s by each element in the list.
⌊/         ⍝ Finally go over the list accumulating the minimum.

You can try it online!
Previous 10 byte solution:
d÷⌈/s÷⍨d-p

Explanation:
       d-p ⍝ Find the distance each horse still has to travel
    s÷⍨    ⍝ and divide it by each horse's speed.
  ⌈/       ⍝ Now go over the list, accumulating the maximum.
d÷         ⍝ Finally divide the distance by that time.

You can try it online!
Thanks to @Grimmy for spotting a (now corrected) problem with my original answer and for saving me 1 byte.

+1 Nice first APL answer. Since your code is an expression, you can simply wrap it in a dummy program. The variables retain their values and will print when mentioned. Try it online!

@Adám wow this is really cool! I may like APL more than Jelly :p

You're always welcome to hang out in the APL Orchard. Great place to ask questions and get tips, advice, and all kinds of help.

@Grimmy Thank you for your attentive eye! You will be pleased to know I already corrected my error!

Nice fix! I don't know APL, but you might be able to save bytes by porting my simplified formula, o=min(x.s/(1-x.p/d)for x in h).

I don't know much APL either but I was able to shave 1 byte :) Good job here (y)

Python 3, 31 bytes
o=d/max((d-x.p)/x.s for x in h)

This challenge is actually much simpler than it seems. In order to avoid running in to other horses, you have to arrive at the end after whichever horse (not counting Sarah's) arrives at the end last. To go fastest, it is thus best to arrive at exactly the same time as that horse does.
Testing code:
import random
d=random.uniform(200, 1000)
h=[]
class Horse:__slots__=("p", "s")
for _ in range(random.randint(10, 40)):
    h.append(Horse())
    h[-1].p = random.uniform(0, d)
    h[-1].s = random.uniform(5, 10)

It is easier than it seems for sure.  I decided if I ever want to do a more challenging problem I could require that the program can return the position horse "x" and time "t" given whatever distance and horses.

I was litterally just about to say 'You do not initialize h in your test code.  Adding "h = []" as line 3 fixed this for me'.  Nice job catching it first.

Your byte count is incorrect; I count 31 bytes. Additionally, you may not take input in the form of a variable; you must either declare a function, an anonymous lambda, or create a full program.

Wait never mind, ignore what I said. I didn't read the part in the specs saying you were supposed to assume that they were in scope. Carry on, +1 :)

This formula can be simplified to o=min(x.s/(1-x.p/d)for x in h). TIO link to check that the two are equivalent.

05AB1E, 5 bytes
/1α/ß

Try it online!

Pyth, 16 bytes * 1.25 = 20 bytes
=ZcdeS.ec-dhbebH

Most of this is dedicated to preserving the input format.
Used H instead of h because h isn't a variable in Pyth
While I could've taken that o isn't a variable as an excuse to use J or K and save a byte, in the end I decided to use Z (zerO) because it's what I would've had to do if o was available.
Try it online!

Why are you multiplying the byte count by 1.25?

@RGS Some challenge specific rule :/