|
1 | 1 | { |
2 | 2 | "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "code", |
| 5 | + "execution_count": null, |
| 6 | + "metadata": {}, |
| 7 | + "outputs": [], |
| 8 | + "source": [ |
| 9 | + "#!/bin/python3\n", |
| 10 | + "\n", |
| 11 | + "import math\n", |
| 12 | + "import os\n", |
| 13 | + "import random\n", |
| 14 | + "import re\n", |
| 15 | + "import sys\n", |
| 16 | + "\n", |
| 17 | + "# PROBLEM: Given an array of integers (arr) and a target value (k) determine the number of pairs of array elements that have a difference equal to target value\n", |
| 18 | + "# https://www.hackerrank.com/challenges/pairs/problem?isFullScreen=true\n", |
| 19 | + "\n", |
| 20 | + "# ===== EXAMPLE ===== #\n", |
| 21 | + "# k = 1\n", |
| 22 | + "# arr = [1,2,3,4]\n", |
| 23 | + "# ---> (2,1), (3,2), (4,3) = 3 Pairs\n", |
| 24 | + "\n", |
| 25 | + "# BRUTE FORCE APPROACH:\n", |
| 26 | + "# STEP 1: Generate every combination of pairs (i,j) in the array\n", |
| 27 | + "# STEP 2: Calculate the difference between i and j\n", |
| 28 | + "# STEP 3: If the difference equals equals the target value, increment count by 1\n", |
| 29 | + "\n", |
| 30 | + "def pairs(k, arr):\n", |
| 31 | + " count = 0\n", |
| 32 | + " for i in range(len(arr)):\n", |
| 33 | + " for j in range(i+1, len(arr)):\n", |
| 34 | + " if (arr[i] - arr[j] == k) or (arr[j] - arr[i] == k):\n", |
| 35 | + " count += 1\n", |
| 36 | + " return count\n", |
| 37 | + "\n", |
| 38 | + "if __name__ == '__main__':\n", |
| 39 | + " fptr = open(os.environ['OUTPUT_PATH'], 'w')\n", |
| 40 | + "\n", |
| 41 | + " first_multiple_input = input().rstrip().split()\n", |
| 42 | + "\n", |
| 43 | + " n = int(first_multiple_input[0])\n", |
| 44 | + "\n", |
| 45 | + " k = int(first_multiple_input[1])\n", |
| 46 | + "\n", |
| 47 | + " arr = list(map(int, input().rstrip().split()))\n", |
| 48 | + "\n", |
| 49 | + " result = pairs(k, arr)\n", |
| 50 | + "\n", |
| 51 | + " fptr.write(str(result) + '\\n')\n", |
| 52 | + "\n", |
| 53 | + " fptr.close()\n" |
| 54 | + ] |
| 55 | + }, |
3 | 56 | { |
4 | 57 | "cell_type": "code", |
5 | 58 | "execution_count": null, |
|
20 | 73 | " # k = 1\n", |
21 | 74 | " # arr = [1,2,3,4]\n", |
22 | 75 | " # ---> (2,1), (3,2), (4,3) = 3 Pairs\n", |
23 | | - "# APPROACH:\n", |
| 76 | + "# OPTIMIZED APPROACH:\n", |
24 | 77 | "# STEP 1: Generate every combination of pairs (i,j) in the array\n", |
25 | 78 | "# STEP 2: Calculate the difference between i and j\n", |
26 | 79 | "# STEP 3: If the difference equals equals the target value, increment count by 1\n", |
|
0 commit comments