Help me in solving TACHSTCK problem

My issue

n,d=map(int,input().split())
l=list(map(int,input().split()))
l.sort()
c,i=0,0
while i < n - 1:
if l[i + 1] - l[i] <= d:
c += 1
i += 2
else:
i += 1

print(c)

what is wrong with this code getting this error

Traceback (most recent call last):
File “/mnt/sol.py”, line 6, in
if l[i + 1] - l[i] <= d:
IndexError: list index out of range

My code

n,d=map(int,input().split())
l=list(map(int,input().split()))
l.sort()
c,i=0,0
while i < n - 1:
    if l[i + 1] - l[i] <= d:
        c += 1
        i += 2  
    else:
        i += 1

print(c)        

Learning course: Greedy Algorithms
Problem Link: CodeChef: Practical coding for everyone

@singhaditi2004
Plzz refer the following solution for better understanding of logic and implementation.

n, d = map(int, input().split())

lengths = []
for _ in range(n):
    lengths.append(int(input()))

lengths.sort()

count = 0
i = 0
while(i < n - 1):
    if abs(lengths[i] - lengths[i + 1]) <= d:
        count += 1
        i += 2
    else:
        i += 1
print(count)
    ```

Thank you !!