Easy to understand Java solution

  • 0

    Iterate from end to start. Switch when first found the smallest element in the tail part and then swap. Concat these chars to a strign and convert to a number.
    Otherwise, return -1.

    public int nextGreaterElement(int n) {
            if(n<10) return -1;
            char[] num = Integer.valueOf(n).toString().toCharArray();
            int i = num.length-1;
            	char[] tail = Arrays.copyOfRange(num, i, num.length);
            	for(int j=0;j<tail.length;j++){
            		if(tail[j]>num[i-1]) {
            			char swap = tail[j];
            			num[i-1] = swap;
            			String head = new String(Arrays.copyOf(num, i));
            			String nextGreater = head + new String(tail);
            				return Integer.parseInt(nextGreater);
            			}catch (Exception ex){
            				return -1;
            return -1;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.