Practice #5
Lesson 14 of 14 in Coddy's Doubly Linked List - Data Structures Series #6 course.
Challenge
EasyGiven a sorted integer array arr (the values of a sorted doubly linked list) and an integer target, write a function countPairs that returns the number of pairs of indices (i, j) with i < j and arr[i] + arr[j] == target.
Assume the input contains no duplicate values.
Use a doubly linked list to solve this problem! Two pointers from both ends, moving inward.
You must use the DoublyLinkedList class (provided in doublylinkedlist.<ext> along with node.<ext>) — do not use language built-ins like arrays' reverse, slicing, sort, or stdlib list operations to compute the result.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "solution.h"
int main() {
char line1[8192];
char line2[64];
if (!fgets(line1, sizeof(line1), stdin)) line1[0] = '\0';
if (!fgets(line2, sizeof(line2), stdin)) line2[0] = '\0';
int arr[4096];
int len = 0;
char* tok = strtok(line1, " \t\r\n");
while (tok) { arr[len++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
int n = atoi(line2);
int r = countPairs(arr, len, n);
printf("%d\n", r);
return 0;
}