REVLINK - Editorial

PROBLEM LINK:

Practice
Contest

Author: Yash Shah
Tester: Roshan Gupta, Shivam Sarang, Hrishikesh Patel
Editorialist: Yash Shah

DIFFICULTY:

EASY-MEDIUM

PROBLEM:

Chef loves coding questions which involves traversing of reversed
Linked List.

But Chef is stuck in a question where he has to print the
first occurrence of the Nth node value from the end of a Singly Linked
List of length L.

Can you help him out of this?

Note: If length of Singly Linked List is less than N print -1.

Input Format:

  • First line contains T number of test cases.
  • First line contains two space separated integers L, N where L is
    length of the linked list and the N is index of the node starting from
    end whose value is to be determined.
  • Second line contains A1,A2,…AL value of the linked list nodes
    starting from the head.

Output Format:

  • A single digit result which satisfies the problem.

EXPLANATION:

Sample Test Case:

Input:
3
10 5
100 20 123 342 23 123 3423 343 12 4
7 2
78 90 78 3 7 78 1011
5 6
100 232 9 1003 89

Output:
8
7
-1

  • Test Case1: If we traverse 5 elements from end we get 123. And
    the first occurrence of 123 is at 2nd index, so from end it is at 8th
    index. Hence Result: 8
  • Test Case 2: If we traverse 2 elements from end we get 78. And
    the first occurrence of 78 is at 0th index, so from end it is 7th index.
    Hence Result: 7

SOLUTIONS:

Setter's Solution
import sys
import numpy as np
t = int(input())
while t:
    ele = 0
    arr = list(map(int, sys.stdin.readline().split()))
    L, N = arr[0], arr[1]
    if L > N:
        lst = list(map(int, sys.stdin.readline().split()))
        if len(lst) == L:
            ele = lst[-N]
        arr = np.array(lst)
        pos = np.where(arr == ele)[0]
        print(len(lst) - pos[0])
    else:
        lst = list(map(int, sys.stdin.readline().split()))
        print(-1)
        t -= 1