C - Shortest Duplicate Subarray
Source: atcoder
Difficulty: 300

Problem Statement
You are given a positive integer
N
and an integer sequence
A = (A_1,A_2,\dots,A_N)
of length
N
.
Determine whether there exists a non-empty (contiguous) subarray of
A
that has a repeated value, occurring multiple times in
A
. If such a subarray exists, find the length of the shortest such subarray.
Constraints
1 \leq N \leq 2 \times 10^5
1 \leq A_i \leq 10^6 \ (1 \leq i \leq N)
All input values are integers.
Input
The input is given from Standard Input in the following format:
N
A_1
A_2
\dots
A_N
Output
If there is no (contiguous) subarray satisfying the condition in the problem statement, print
-1
. Otherwise, print the length of the shortest such subarray.
Sample Input 1
5
3 9 5 3 1
Sample Output 1
4
(3,9,5,3)
and
(3,9,5,3,1)
satisfy the condition. The shorter one is
(3,9,5,3)
, which has length
4
.
Sample Input 2
4
2 5 3 1
Sample Output 2
-1
There is no subarray that satisfies the condition.
Sample Input 3
10
1 1 2 3 5 8 13 21 34 55
Sample Output 3
2

C++ solution:
#include <bits/stdc++.h>
using namespace std;
#define REP(i, a, b) for (int i = (a); i < (int)(b); i++)
#define RREP(i, a, b) for (int i = (a); i >= (int)(b); i--)
#define FORE(i,a) for(auto &i:a)
#define ALL(a)  (a).begin(),(a).end()
#define VCIN(x) for(auto&youso_: (x) )cin>>youso_
#define VCOUT(x) for(auto&youso_: (x) )cout<<youso_<<" ";cout<<endl
#define VVCIN(x) for(auto&youso_: (x) )for(auto&youso__: (youso_) )cin>>youso__
#define VVCOUT(x)for(auto&youso_: (x) ){for(auto&youso__: (youso_) )cout<<youso__<<" ";cout<<endl;}
#define COUT(x) cout<<(x)<<endl
#define dCOUT(x) cout<<fixed<<setprecision(10)<<(x)<<endl;

#define ll  long long
#define str string
#define pb push_back
#define eb emplace_back
#define pbc pop_back
#define np next_permutation
#define popcnt __builtin_popcountll
#define VLL vector<ll>
#define VVLL vector<vector<ll>>
#define MLLLL map<ll, ll>
#define STLL set<ll>
#define SKLL stack<ll>
#define QLL queue<ll>
#define PLLLL pair<ll,ll>
#define TLLLLLL tuple<ll,ll,ll>
template<typename T> bool chmin(T& a, T b){if(a > b){a = b; return true;} return false;}
template<typename T> bool chmax(T& a, T b){if(a < b){a = b; return true;} return false;}
template<class T> int getSum(T a) {if (a == 0) return 0;return a % 10 + getSum(a / 10);}
const ll infl = 1LL << 60;
const ll mod = 1000000007;
VLL dx={-1,0,1,0};
VLL dy={0,-1,0,1};

ll gcd(ll x, ll y) {if(y == 0)return x; return gcd(y, x % y); }

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int n;
    cin>>n;
    VLL a(n);
    VLL last_seen(1000009,-1);
    REP(i,0,n){
        cin>>a[i];
    }
    
    ll ans=INT_MAX;
    REP(i,0,n){
        if(last_seen[a[i]]!=-1){
            chmin(ans,i-last_seen[a[i]]+1);
        }
        last_seen[a[i]]=i;
    }
    if(ans==INT_MAX)ans=-1;
    COUT(ans);
}

Go solution:
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func main() {
	defer flush()

	var n int = ni()
	var a []int = nis(n)

	var ans int = math.MaxInt32

	// number to index
	var n2i map[int]int = make(map[int]int)
	for i := 0; i < n; i++ {
		if val, ok := n2i[a[i]]; ok {
			ans = min(ans, i-val+1)
		}
		n2i[a[i]] = i
	}

	if ans == math.MaxInt32 {
		out(-1)
	} else {
		out(ans)
	}
}

func init() {
	scanner.Buffer([]byte{}, math.MaxInt64)
	scanner.Split(bufio.ScanWords)
}

func ni() int {
	scanner.Scan()
	i, e := strconv.Atoi(scanner.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func nis(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ni()
	}
	return a
}

func out(v ...interface{}) {
	_, e := fmt.Fprintln(writer, v...)
	if e != nil {
		panic(e)
	}
}

func flush() {
	e := writer.Flush()
	if e != nil {
		panic(e)
	}
}

func min(values ...int) int {
	ret := values[0]
	for _, v := range values {
		if ret > v {
			ret = v
		}
	}
	return ret
}

func max(values ...int) int {
	ret := values[0]
	for _, v := range values {
		if ret < v {
			ret = v
		}
	}
	return ret
}

Java solution:
import java.util.*;

public class Main {

    public static void main(String[] args) {
        int n = getInt();
        int a[] = getIntArray(n);

        int min = Integer.MAX_VALUE;

        HashMap<Integer, Integer> map = new HashMap<>();

        for(int i = 0;i < n;i++){
            if(map.containsKey(a[i])){
                min = Math.min(min, i - map.get(a[i]) + 1);
            }
            map.put(a[i], i);
        }

        out(min == Integer.MAX_VALUE ? -1 : min);
    }


    static int[] dx = new int[]{1, 0, -1, 0};
    static int[] dy = new int[]{0, 1, 0, -1};
    static Comparator<Long> lower = (x, y) -> x.compareTo(y) >= 0 ? 1 : -1; // 指定した値以上の初めての要素の位置
    static Comparator<Long> upper = (x, y) -> x.compareTo(y) > 0 ? 1 : -1;// 指定した値より大きい初めての要素の位置

    static Map<Integer, Set<Integer>> createEdgeMap(int m) {
        return createEdgeMap(m, false);
    }

    static Map<Integer, Set<Integer>> createEdgeMap(int m, boolean d){
        Map<Integer, Set<Integer>> edges = new HashMap<>();

        for(int i = 0;i < m;i++){
            int u = getInt();
            int v = getInt();
            edges.computeIfAbsent(u, key->new HashSet<>()).add(v);
            if(!d) edges.computeIfAbsent(v, key->new HashSet<>()).add(u);
        }

        return edges;
    }

    static long ceil(long n, long d){
        return (n + d - 1) / d;
    }

    static int sqrtI(long n){
        return toInt(Math.sqrt(n));
    }

    static long toLong(double v) {
        return Double.valueOf(v).longValue();
    }

    static int toInt(double v) {
        return Double.valueOf(v).intValue();
    }

    static String[] createTiles(int w, int h, String out){
        String[] s = new String[h + 2];
        s[0] = s[h + 1] = out.repeat(w + 2);

        for (int i = 1; i <= h; i++) {
            s[i] = out + getString() + out;
        }
        return s;
    }

    static void outH(List<?> o){
        int nl = o.size()-1;
        for (int i = 0; i < o.size(); i++) {
            System.out.print(o.get(i)+(i != nl ? " ":"\n"));
        }
    }
    static void out(List<?> o){
        for (Object oo: o) {
            System.out.println(oo);
        }
    }

    static void outH(Object[] o){
        int nl = o.length-1;
        for (int i = 0; i < o.length; i++) {
            System.out.print(o[i]+(i != nl ? " ":""));
        }
        out();
    }

    static void outH(char[] d){
        int nl = d.length-1;
        for (int i = 0; i < d.length; i++) {
            System.out.print(d[i]+(i != nl ? " ":""));
        }
        out();
    }

    static void outH(double[] d){
        int nl = d.length-1;
        for (int i = 0; i < d.length; i++) {
            System.out.print(d[i]+(i != nl ? " ":""));
        }
        out();
    }

    static void outH(int[] in){
        int nl = in.length-1;
        for (int i = 0; i < in.length; i++) {
            System.out.print(in[i]+(i != nl ? " ":""));
        }
        out();
    }

    static void outH(long[] l){
        int nl = l.length-1;
        for (int i = 0; i < l.length; i++) {
            System.out.print(l[i]+(i != nl ? " ":""));
        }
        out();
    }
    static void outH(String[] s){
        int nl = s.length-1;
        for (int i = 0; i < s.length; i++) {
            System.out.print(s[i]+(i != nl ? " ":""));
        }
        out();
    }

    static void out(){
        System.out.println();
    }

    static void out(Object[] o){
        for (Object oo : o) {
            System.out.println(oo);
        }
    }

    static String sortString(String s) {
        char[] a = s.toCharArray();
        Arrays.sort(a);
        return new String(a);
    }

    static String sortStringDesc(String s) {
        return new StringBuilder(sortString(s)).reverse().toString();
    }

    static void out(char[] c){
        for (Character aChar : c) {
            System.out.println(aChar);
        }
    }

    static void out(double[] d){
        for (Double aDouble : d) {
            System.out.println(aDouble);
        }
    }

    static void out(int[] i){
        for (Integer iInteger: i) {
            System.out.println(iInteger);
        }
    }

    static void out(long[] l){
        for (Long lLong: l) {
            System.out.println(lLong);
        }
    }
    static void out(String[] s){
        for (String sString: s) {
            System.out.println(sString);
        }
    }

    static void out(Double d){
        System.out.println(d);
    }


    static void out(Integer i){
        System.out.println(i);
    }

    static void out(Long l){
        System.out.println(l);
    }
    static void out(String s){
        System.out.println(s);
    }

    static void YesOrNo(boolean b){
        System.out.println(b ? "Yes" : "No");
    }
    static void YesOrNo(boolean b, String yes, String no){
        System.out.println(b ? yes : no);
    }
    static void Yes(){
        System.out.println("Yes");
    }

    static void No(){
        System.out.println("No");
    }

    /*
    static StringTokenizer st;
    static InputStreamReader isr = new InputStreamReader(System.in);
    static BufferedReader br = new BufferedReader(isr);
    static String getString()  {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine().trim());
            } catch (IOException e) {
                System.exit(0);
            }
        }
        return st.nextToken();
    }
    static long getLong() {
        return Long.parseLong(getString());
    }
    static int getInt()  {
        return Integer.parseInt(getString());
    }

    static Double getDouble() {
        return parseDouble(getString());
    }

     */
    private static final java.io.InputStream in = System.in;
    private static final byte[] buffer = new byte[1024];
    private static int ptr = 0;
    private static int buflen = 0;

    private static final long LONG_MAX_TENTHS = 922337203685477580L;
    private static final int LONG_MAX_LAST_DIGIT = 7;
    private static final int LONG_MIN_LAST_DIGIT = 8;

    static boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (java.io.IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    static int readByte() {
        if (hasNextByte()) return buffer[ptr++]; else return -1;
    }
    static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }
    static boolean hasNext() {
        while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
        return hasNextByte();
    }
    static String getString() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    static long getLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                int digit = b - '0';
                if (n >= LONG_MAX_TENTHS) {
                    if (n == LONG_MAX_TENTHS) {
                        if (minus) {
                            if (digit <= LONG_MIN_LAST_DIGIT) {
                                n = -n * 10 - digit;
                                b = readByte();
                                if (!isPrintableChar(b)) {
                                    return n;
                                } else if (b < '0' || '9' < b) {
                                    throw new NumberFormatException(
                                            String.format("%d%s... is not number", n, Character.toString(b))
                                    );
                                }
                            }
                        } else {
                            if (digit <= LONG_MAX_LAST_DIGIT) {
                                n = n * 10 + digit;
                                b = readByte();
                                if (!isPrintableChar(b)) {
                                    return n;
                                } else if (b < '0' || '9' < b) {
                                    throw new NumberFormatException(
                                            String.format("%d%s... is not number", n, Character.toString(b))
                                    );
                                }
                            }
                        }
                    }
                    throw new ArithmeticException(
                            String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)
                    );
                }
                n = n * 10 + digit;
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    static public int getInt() {
        long nl = getLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }
    static public double getDouble() {
        return Double.parseDouble(getString());
    }

    static public Long[] getLongArray(int length){
        Long[] array = new Long[length];
        for(int i=0; i<length; i++) array[i] = getLong();
        return array;
    }
    static public Long[] getLongArray(int length, java.util.function.LongUnaryOperator map){
        Long[] array = new Long[length];
        for(int i=0; i<length; i++) array[i] = map.applyAsLong(getLong());
        return array;
    }
    static public int[] getIntArray(int length){
        int[] array = new int[length];
        for(int i=0; i<length; i++) array[i] = getInt();
        return array;
    }
    static public int[] getIntArray(int length, java.util.function.IntUnaryOperator map){
        int[] array = new int[length];
        for(int i=0; i<length; i++) array[i] = map.applyAsInt(getInt());
        return array;
    }
    static public double[] getDoubleArray(int length){
        double[] array = new double[length];
        for(int i=0; i<length; i++) array[i] = getDouble();
        return array;
    }
    static public double[] getDoubleArray(int length, java.util.function.DoubleUnaryOperator map){
        double[] array = new double[length];
        for(int i=0; i<length; i++) array[i] = map.applyAsDouble(getDouble());
        return array;
    }

    static public long[][] getLongMatrix(int height, int width){
        long[][] mat = new long[height][width];
        for(int h=0; h<height; h++) for(int w=0; w<width; w++){
            mat[h][w] = getLong();
        }
        return mat;
    }
    static int[][] getIntMatrix(int height, int width){
        int[][] mat = new int[height][width];
        for(int h=0; h<height; h++) for(int w=0; w<width; w++){
            mat[h][w] = getInt();
        }
        return mat;
    }
    static public double[][] getDoubleMatrix(int height, int width){
        double[][] mat = new double[height][width];
        for(int h=0; h<height; h++) for(int w=0; w<width; w++){
            mat[h][w] = getDouble();
        }
        return mat;
    }

    static public char[][] nextCharMatrix(int height, int width){
        char[][] mat = new char[height][width];
        for(int h=0; h<height; h++){
            String s = getString();
            for(int w=0; w<width; w++){
                mat[h][w] = s.charAt(w);
            }
        }
        return mat;
    }
    public static long mod1097 = 1000000007L;
    public static long mod9982 = 998244353L;
}

JavaScript solution:
"use strict";

class Scanner {
    constructor() {
        this.Separator = ' ';
        this._readAllLines();
    }

    _readAllLines() {
        const fs = require('fs');
        const input = fs.readFileSync('/dev/stdin', 'utf8');
        this._lines = input.split('\n');
        this._lineIndex = 0;
        this._readLine();
    }

    _readLine() {
        this._line = this._lines[this._lineIndex].split(this.Separator);
        this._lineLength = this._line.length;
        this._cursorIndex = 0;
    }

    _next() {
        if (this._cursorIndex >= this._lineLength) {
            this._lineIndex++;
            this._readLine();
        }
        const next = this._line[this._cursorIndex];
        this._cursorIndex++;
        return next;
    }

    nextString() {
        return this._next();
    }

    nextInt() {
        return parseInt(this._next(), 10);
    }

    nextLong() {
        return BigInt(this._next());
    }

    nextDouble() {
        return parseFloat(this._next());
    }

    nextDecimal() {
        return parseFloat(this._next());
    }

    nextChar() {
        return this._next().charAt(0);
    }

    nextCharArray() {
        return this._next().split('');
    }

    array() {
        if (this._cursorIndex >= this._lineLength) {
            this._lineIndex++;
            this._readLine();
        }
        this._cursorIndex = this._lineLength;
        return this._line;
    }

    intArray() {
        return this.array().map(Number);
    }

    longArray() {
        return this.array().map(BigInt);
    }

    doubleArray() {
        return this.array().map(Number);
    }

    decimalArray() {
        return this.array().map(Number);
    }
}

function main() {
    const sc = new Scanner();

    const n = sc.nextInt();
    const aa = sc.intArray();

    const map = [];
    for (let i = 0; i <= 1000000; i++) {
        map[i] = -1;
    }

    let answer = -1;
    for (let i = 0; i < n; i++) {
        const num = aa[i];
        if (map[num] !== -1) {
            const diff = i - map[num] + 1;
            if (answer === -1) {
                answer = diff;
            } else {
                answer = Math.min(diff, answer);
            }
        }
        map[num] = i;
    }

    console.log(answer);
}

main();

Python solution:
N=int(input())

A=list(map(int,input().split()))

C=[0]*(10**6+1)

d=2*10**5+1

now=0

for i in range(N):
    if C[A[i]]:
        now=i-C[A[i]]+2
        if now<d:
            d=now
    C[A[i]]=i+1

if not now:
    print(-1)
else:
    print(d)

Ruby solution:
N = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)
# arrs = readlines.map(&:split.map(&:to_i))

# 同じものがある値を取得
# その値は何番目と何番目にあるか判定する
# その長さを出す


# ハッシュに入れて順番にキー判定
# インデックスも入れておき、何番目か判定する

result = []
hash = {}
N.times.map do |i| 
  if hash[arr[i]].nil?
    hash[arr[i]] = i 
  else
    fst = hash[arr[i]]
    lst = i
    result << lst - fst + 1
  end
end

puts result.size.zero? ? -1 : result.min