Skip to content

Commit 726977e

Browse files
committed
Added extra solutions to HackerRank problems
1 parent fa3a272 commit 726977e

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

Pairs.ipynb

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,58 @@
11
{
22
"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+
},
356
{
457
"cell_type": "code",
558
"execution_count": null,
@@ -20,7 +73,7 @@
2073
" # k = 1\n",
2174
" # arr = [1,2,3,4]\n",
2275
" # ---> (2,1), (3,2), (4,3) = 3 Pairs\n",
23-
"# APPROACH:\n",
76+
"# OPTIMIZED APPROACH:\n",
2477
"# STEP 1: Generate every combination of pairs (i,j) in the array\n",
2578
"# STEP 2: Calculate the difference between i and j\n",
2679
"# STEP 3: If the difference equals equals the target value, increment count by 1\n",

0 commit comments

Comments
 (0)