• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Friday, January 27, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Airports – HackerRank Solution

Airports - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
May 27, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Airports – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ Airports HackerRank Solution
  • Java Airports HackerRank Solution
  • Python 3 Airports HackerRank Solution
  • C Airports HackerRank Solution
    • Warmup Implementation Strings Sorting Search Graph Theory Greedy Dynamic Programming Constructive Algorithms Bit Manipulation Recursion Game Theory NP Complete Debugging
    • Leave a comment below
      • Related posts:

Airports – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

C++ Airports HackerRank Solution


Copy Code Copied Use a different Browser

	#include <bits/stdc++.h>
	using namespace std;
	template<class T,class U>
	ostream &operator<<(ostream &os,const pair<T,U> &x) {
		return os<<"("<<x.first<<","<<x.second<<")";
	}
	namespace dbg_ns {
		template<typename C>
		struct is_iterable {
			template<class T> static long check(...);
			template<class T> static char check(int,
				typename T::const_iterator = C().end());
			enum {
				value = sizeof(check<C>(0)) == sizeof(char),
				neg_value = sizeof(check<C>(0)) != sizeof(char)
			};
		};
		template<class T> ostream &_out_str(ostream &os,const T &x) {
			return os<<'"'<<x<<'"';
		}
		template<class T> ostream &_dbg2_5(ostream &,const T &);
		template<bool B,typename T=void> using eit=typename enable_if<B,T>::type;
		template<class T>
		inline ostream &_dbg3(ostream &os,eit<is_iterable<T>::neg_value,const T> &x) {
			return os<<x;
		}
		template<class T>
		inline ostream &_dbg3(ostream &os,eit<is_iterable<T>::value,const T> &V) {
			os<<"{";
			bool ff=0;
			for(const auto &E:V) _dbg2_5(ff?os<<",":os,E), ff=1;
			return os<<"}";
		}
		template<>
		inline ostream &_dbg3<string>(ostream &os,const string &x) {
			return _out_str(os,x);
		}
		template<>
		inline ostream &_dbg3<const char *>(ostream &os,const char *const &x) {
			return _out_str(os,x);
		}
		template<class T> inline ostream &_dbg2_5(ostream &os,const T &x) {
			return _dbg3<T>(os,x);
		}
		template<class T,typename... Args> ostream &_dbg2(ostream &os,vector<string>::iterator nm,const T &x,Args&&... args);
		inline ostream &_dbg2(ostream &os,vector<string>::iterator) { return os; }
		template<typename... Args>
		inline ostream &_dbg2(ostream &os,vector<string>::iterator nm,const char *x,Args&&... args) {
			return _dbg2(_dbg3<const char *>(os<<"  ",x),nm+1,args...);
		}
		template<class T,typename... Args>
		inline ostream &_dbg2(ostream &os,vector<string>::iterator nm,const T &x,Args&&... args) {
			return _dbg2(_dbg3<T>(os<<"  "<<*nm<<"=",x),nm+1,args...);
		}
		vector<string> split(string s) {
			vector<string> Z;
			string z="";
			s+=',';
			int dep=0;
			for(char c:s) {
				if(c==',' && !dep) Z.push_back(z),z="";
				else z+=c;
				if(c=='(') ++dep;
				if(c==')') --dep;
			}
			return Z;
		}
		template<typename... Args> inline ostream &_dbg1(int ln,const string &nm,Args&&... args) {
			auto nms=split(nm);
			return _dbg2(cerr<<"L"<<ln<<":",nms.begin(),args...)<<endl;
		}
	}
	#define dbg(...) dbg_ns::_dbg1(__LINE__,#__VA_ARGS__,__VA_ARGS__)
	#define sz(x) (int(x.size()))
	#define eprintf(...) fprintf(stderr,__VA_ARGS__)
	#define fi first
	#define se second
	#define pb push_back
// END SUBLIME HAX
// #include <bits/extc++.h>
// using namespace __gnu_pbds;
typedef unsigned long long ull;
typedef long long ll;
typedef long double ld; //CARE
typedef complex<ld> pt;
const ld eps=(ld)1e-8;
const ld tau=2*(ld)acosl(-1);
const int inf=1e9+99;
const ll linf=1e18+99;
const int P=1e9+7;





int n;
int hi,lo;
set<int> ss;
set<pair<int,int> > ww;

void kill(int x) {
	auto it=ss.lower_bound(x);
	assert(*it==x);
	++it;
	if(it==ss.end()) return;
	int y=*it;
	pair<int,int> key={y-x,x};
	if(ww.count(key)) ww.erase(key);
}
void add(int x) {
	auto it=ss.lower_bound(x);
	assert(*it==x);
	++it;
	if(it==ss.end()) return;
	int y=*it;
	ww.insert({y-x,x});
}


void ins(int x) {
	auto it=ss.lower_bound(x);
	if(it!=ss.end() && *it==x) return;
	int y=inf;
	if(it!=ss.begin()) {
		--it;
		y=*it;
		kill(y);
	}
	ss.insert(x);
	if(y!=inf) add(y);
	add(x);
}
void RZ() {
	n=0;
	ss.clear();
	ww.clear();
}
void INS(int x) {
	if(!n) {
		hi=lo=x;
		n=1;
		return;
	}
	if(n==1) {
		hi=max(hi,x);
		lo=min(lo,x);
		n=2;
		return;
	}

	++n;
	if(x>hi) {
		ins(hi);
		hi=x;
		return;
	}
	if(x<lo) {
		ins(lo);
		lo=x;
		return;
	}
	ins(x);
}
int Q(int d) {
	if(n==1) return 0;
	assert(sz(ss)<=n-2);
	if(n==2) return max(0,d-(hi-lo));


	// dbg(ss,ww,lo,hi);

	int Z=inf;
	auto it=ss.lower_bound(hi-d+1);
	if(it==ss.end()) return 0;
	if(*it>=lo+d) return 0;
	Z=min(Z,max(0,d-(*it-lo)));
	it=ss.lower_bound(lo+d);
	--it;
	Z=min(Z,max(0,d-(hi-*it)));


	for(;;) {
		auto it=ww.end();
		if(it==ww.begin()) {
			break;
		}
		--it;
		if(it->se<hi-d || it->se+it->fi>lo+d) {
			ww.erase(it);
		} else {
			break;
		}
	}
	auto it2=ww.end();
	if(it2!=ww.begin()) {
		--it2;
		Z=min(Z,max(0,d+d-(hi-lo)-it2->fi));
	}
	return Z;
}



void _m() {
	int n,d;
	scanf("%d%d",&n,&d);
	RZ();
	for(;n--;) {
		int x; scanf("%d",&x);
		INS(x);
		printf("%d%c",Q(d)," \n"[!n]);
	}
}


int32_t main() {
	int q; scanf("%d",&q);
	for(;q--;) _m();
}











Java Airports HackerRank Solution


Copy Code Copied Use a different Browser

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Random;

public class F {
	InputStream is;
	PrintWriter out;
	String INPUT = "";
//	String INPUT = "1 4 4\r\n" + 
//			"-3 1 0 -2 ";
	
	// -2 -2 -1 -1
	
	void solve()
	{
		for(int T = ni();T > 0;T--){
			int n = ni();
			int d = ni();
			if(d == 0){
				for(int i = 0;i < n;i++){
					ni();
					out.print(0 + " ");
				}
				out.println();
				continue;
			}
			
			Node root = null;
			int minx = Integer.MAX_VALUE;
			int maxx = Integer.MIN_VALUE;
			for(int i = 0;i < n;i++){
				int x = ni();
				Node my = new Node(x, 0);
				minx = Math.min(minx, x);
				maxx = Math.max(maxx, x);
				root = insertb(root, my);
				Node next = next(my);
				if(next != null){
					my.v = next.pos - my.pos;
					propagate(my);
				}
				Node prev = prev(my);
				if(prev != null){
					prev.v = my.pos - prev.pos;
					propagate(prev);
				}
				
				int r = lowerBound(root, minx + d)-1;
				int l = lowerBound(root, maxx - d + 1)-1;
//				tr(i);
//				for(Node no : nodes(root))tr(no.v, no.pos);
				// -3 -2 0 1
//				tr(l, r);
				int ans = Integer.MAX_VALUE;
				// [0,l] : >=d
				// [r,last]: >=d
				
				if(r <= l || i == 0){
					ans = 0;
				}else{
					{
//						Node L = get(root, 0);
						Node R = get(root, 1);
						int can = Math.max(d-(R.pos-minx), 0);
						ans = Math.min(ans, can);
					}
					{
						Node L = get(root, count(root)-2);
//						Node R = get(root, count(root)-1);
						int can = Math.max(d-(maxx-L.pos), 0);
						ans = Math.min(ans, can);
					}
					if(l >= 0 && l+1 < count(root)){
						Node L = get(root, l);
						Node R = get(root, l+1);
						int can = Math.max(d-(R.pos-minx), 0) + Math.max(d-(maxx-L.pos), 0);
						ans = Math.min(ans, can);
					}
					if(r >= 0 && r+1 < count(root)){
						Node L = get(root, r);
						Node R = get(root, r+1);
						int can = Math.max(d-(R.pos-minx), 0) + Math.max(d-(maxx-L.pos), 0);
						ans = Math.min(ans, can);
					}
					ans = Math.min(ans, 2*d-(maxx-minx)-max(root, l+1, r));
				}
				out.print(ans + " ");
			}
			out.println();
		}
	}
	
	public static Node next(Node x)
	{
		if(x == null)return null;
		if(x.right != null){
			x = x.right;
			while(x.left != null)x = x.left;
			return x;
		}else{
			while(true){
				Node p = x.parent;
				if(p == null)return null;
				if(p.left == x)return p;
				x = p;
			}
		}
	}
	
	public static Node prev(Node x)
	{
		if(x == null)return null;
		if(x.left != null){
			x = x.left;
			while(x.right != null)x = x.right;
			return x;
		}else{
			while(true){
				Node p = x.parent;
				if(p == null)return null;
				if(p.right == x)return p;
				x = p;
			}
		}
	}
	
	
	public static Random gen = new Random();
	
	static public class Node
	{
		public int v; // value
		public int pos;
		public long priority;
		public Node left, right, parent;
		
		public int count;
		
		public int max; 
		
		public Node(int pos, int v)
		{
			this.pos = pos;
			this.v = v;
			priority = gen.nextLong();
			update(this);
		}
		
		@Override
		public String toString() {
			StringBuilder builder = new StringBuilder();
			builder.append("Node [v=");
			builder.append(v);
			builder.append(", count=");
			builder.append(count);
			builder.append(", parent=");
			builder.append(parent != null ? parent.v : "null");
			builder.append(", max=");
			builder.append(max);
			builder.append("]");
			return builder.toString();
		}
	}

	public static Node update(Node a)
	{
		if(a == null)return null;
		a.count = 1;
		if(a.left != null)a.count += a.left.count;
		if(a.right != null)a.count += a.right.count;
		
		a.max = a.v;
		if(a.left != null)a.max = Math.max(a.left.max, a.max);
		if(a.right != null)a.max = Math.max(a.right.max, a.max);
		return a;
	}
	
	public static Node disconnect(Node a)
	{
		if(a == null)return null;
		a.left = a.right = a.parent = null;
		return update(a);
	}
	
	public static Node root(Node x)
	{
		if(x == null)return null;
		while(x.parent != null)x = x.parent;
		return x;
	}
	
	public static int count(Node a)
	{
		return a == null ? 0 : a.count;
	}
	
	public static void setParent(Node a, Node par)
	{
		if(a != null)a.parent = par;
	}
	
	public static int max(Node a, int L, int R)
	{
		if(a == null || L >= R || L >= count(a) || R <= 0)return -Integer.MAX_VALUE / 3;
		if(L <= 0 && R >= count(a)){
			return a.max;
		}else{
			int lmax = max(a.left, L, R);
			int rmax = max(a.right, L-count(a.left)-1, R-count(a.left)-1);
			int max = Math.max(lmax, rmax);
			if(L <= count(a.left) && count(a.left) < R)max = Math.max(max, a.v);
			return max;
		}
	}
	
	public static void propagate(Node a)
	{
		while(a != null){
			update(a);
			a = a.parent;
		}
	}
	
	public static Node merge(Node a, Node b)
	{
		if(b == null)return a;
		if(a == null)return b;
		if(a.priority > b.priority){
			setParent(a.right, null);
			setParent(b, null);
			a.right = merge(a.right, b);
			setParent(a.right, a);
			return update(a);
		}else{
			setParent(a, null);
			setParent(b.left, null);
			b.left = merge(a, b.left);
			setParent(b.left, b);
			return update(b);
		}
	}
	
	// [0,K),[K,N)
	public static Node[] split(Node a, int K)
	{
		if(a == null)return new Node[]{null, null};
		if(K <= count(a.left)){
			setParent(a.left, null);
			Node[] s = split(a.left, K);
			a.left = s[1];
			setParent(a.left, a);
			s[1] = update(a);
			return s;
		}else{
			setParent(a.right, null);
			Node[] s = split(a.right, K-count(a.left)-1);
			a.right = s[0];
			setParent(a.right, a);
			s[0] = update(a);
			return s;
		}
	}
	
	public static Node insert(Node a, int K, Node b)
	{
		if(a == null)return b;
		if(b.priority < a.priority){
			if(K <= count(a.left)){
				a.left = insert(a.left, K, b);
				setParent(a.left, a);
			}else{
				a.right = insert(a.right, K-count(a.left)-1, b);
				setParent(a.right, a);
			}
			return update(a);
		}else{
			Node[] ch = split(a, K);
			b.left = ch[0]; b.right = ch[1];
			setParent(b.left, b);
			setParent(b.right, b);
			return update(b);
		}
	}
	
	// delete K-th
	public static Node erase(Node a, int K)
	{
		if(a == null)return null;
		if(K < count(a.left)){
			a.left = erase(a.left, K);
			setParent(a.left, a);
			return update(a);
		}else if(K == count(a.left)){
			setParent(a.left, null);
			setParent(a.right, null);
			Node aa = merge(a.left, a.right);
			disconnect(a);
			return aa;
		}else{
			a.right = erase(a.right, K-count(a.left)-1);
			setParent(a.right, a);
			return update(a);
		}
	}
	
	public static Node get(Node a, int K)
	{
		while(a != null){
			if(K < count(a.left)){
				a = a.left;
			}else if(K == count(a.left)){
				break;
			}else{
				K = K - count(a.left)-1;
				a = a.right;
			}
		}
		return a;
	}
	
	static Node[] Q = new Node[100];
	public static Node update(Node a, int K, int v)
	{
		int p = 0;
		while(a != null){
			Q[p++] = a;
			if(K < count(a.left)){
				a = a.left;
			}else if(K == count(a.left)){
				break;
			}else{
				K = K - count(a.left)-1;
				a = a.right;
			}
		}
		a.v = v;
		while(p > 0){
			update(Q[--p]);
		}
		return a;
	}
	
	public static int index(Node a)
	{
		if(a == null)return -1;
		int ind = count(a.left);
		while(a != null){
			Node par = a.parent;
			if(par != null && par.right == a){
				ind += count(par.left) + 1;
			}
			a = par;
		}
		return ind;
	}
	
	public static Node insertb(Node root, Node x)
	{
		int ind = lowerBound(root, x.pos);
		return insert(root, ind, x);
	}
	
	public static int lowerBound(Node a, int q)
	{
		int lcount = 0;
		while(a != null){
			if(a.pos >= q){
				a = a.left;
			}else{
				lcount += count(a.left) + 1;
				a = a.right;
			}
		}
		return lcount;
	}

	
	public static Node[] nodes(Node a) { return nodes(a, new Node[count(a)], 0, count(a)); }
	public static Node[] nodes(Node a, Node[] ns, int L, int R)
	{
		if(a == null)return ns;
		nodes(a.left, ns, L, L+count(a.left));
		ns[L+count(a.left)] = a;
		nodes(a.right, ns, R-count(a.right), R);
		return ns;
	}
	
	public static String toString(Node a, String indent)
	{
		if(a == null)return "";
		StringBuilder sb = new StringBuilder();
		sb.append(toString(a.left, indent + "  "));
		sb.append(indent).append(a).append("\n");
		sb.append(toString(a.right, indent + "  "));
		return sb.toString();
	}
	
	void run() throws Exception
	{
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		
		long s = System.currentTimeMillis();
		solve();
		out.flush();
		if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
	}
	
	public static void main(String[] args) throws Exception { new F().run(); }
	
	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;
	
	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}
	
	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
	
	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }
	
	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}
	
	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}
	
	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}
	
	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}
	
	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}

 



Python 3 Airports HackerRank Solution


Copy Code Copied Use a different Browser

import sys

from heapq import heappop,heappush,heapify

def airports(min_dist, airports):
    road = sorted(set(airports))
    len_road = len(road)
    answers = []
    
    airport_indices = dict()
    for i,a in enumerate(road):
        airport_indices[a] = i
        
    qty = [0] * len_road
    for a in airports:
        qty[airport_indices[a]] += 1
    
    safe = []
    near_left = []
    near_right = []
    near_both = []
    
    for i in range(len_road-1):
        gap = (i,i+1)
        safe.append(gap)
    
    heapify(near_left)
    heapify(near_right)
    heapify(near_both)
    
    left_airport = 0
    right_airport = len_road-1
    second_left = 1
    second_right = len_road-2
    
    next_airport = list(range(1,len_road)) + ['N']
    prev_airport = ['N']+ list(range(len_road-1))
    
    
    for ap in reversed(airports):
        road_left_airport, road_right_airport = road[left_airport],road[right_airport]
        
        while safe and (road[safe[-1][1]] - road_left_airport < min_dist or road_right_airport - road[safe[-1][0]] < min_dist):
            gap = safe.pop()
            if road[gap[1]] - road_left_airport < min_dist:
                heappush(near_left,(0-road[gap[1]],gap))
            else:
                heappush(near_right,(road[gap[0]],gap))
        
        while near_left and road_right_airport - road[near_left[0][1][0]] < min_dist:
            gap = heappop(near_left)[1]
            heappush(near_both,(road[gap[0]]-road[gap[1]],gap))
        
        while near_right and road[near_right[0][1][1]] - road_left_airport < min_dist:
            gap = heappop(near_right)[1]
            heappush(near_both,(road[gap[0]]-road[gap[1]],gap))
        
        while near_both and (near_both[0][1][0] < left_airport or near_both[0][1][1] > right_airport):
            heappop(near_both)
        
        
        if safe:
            answers.append(0)
        else:
            possible_answers = [min_dist]
            if left_airport != right_airport:
                if qty[left_airport] == 1:
                    possible_answers.append(min_dist + road_left_airport - road[second_left])
                
                if qty[right_airport] == 1:
                    possible_answers.append(min_dist + road[second_right] - road_right_airport)
            
            if near_left:
                possible_answers.append(max(0,min_dist + road_left_airport - road[near_left[0][1][1]]))
            if near_right:
                possible_answers.append(max(0,min_dist + road[near_right[0][1][0]] - road_right_airport))
            if near_both:
                possible_answers.append(0)
                nb = near_both[0][1]
                possible_answers[-1] += max(0,min_dist + road_left_airport - road[nb[1]])
                    
                possible_answers[-1] += max(0,min_dist + road[nb[0]] - road_right_airport)
                
            answers.append(min(possible_answers))
            
            
        ai = airport_indices[ap]
        qty[ai] -= 1
        if qty[ai]:
            continue
        
        
        
            
        while second_left < len_road-1 and qty[second_left] == 0:
            second_left += 1
        
        while second_right > 0 and qty[second_right] == 0:
            second_right -= 1
            
                
        if ai == left_airport or ai == right_airport:
            
            while left_airport < len_road-1 and qty[left_airport] == 0:
                left_airport += 1
            
            while right_airport > 0 and qty[right_airport] == 0:
                right_airport -= 1
            
            second_left = max(second_left, left_airport+1)
            second_right = min(second_right, right_airport-1)
            
            while second_left < len_road-1 and qty[second_left] == 0:
                second_left += 1
            
            while second_right > 0 and qty[second_right] == 0:
                second_right -= 1
                
        else:
            l = prev_airport[ai]
            r = next_airport[ai]
            
            next_airport[l] = r
            prev_airport[r] = l
            
            gap = (l,r)
            
            safe.append(gap)
        
    answers.reverse()
    answers[0] = 0
    
    return answers



if __name__ == "__main__":
    q = int(input().strip())
    for a0 in range(q):
        n, d = input().strip().split(' ')
        n, d = [int(n), int(d)]
        x = list(map(int, input().strip().split(' ')))
        result = airports(d, x)
        print (" ".join(map(str, result)))




C Airports HackerRank Solution


Copy Code Copied Use a different Browser

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>


typedef struct node_t{
	struct node_t *left;
	struct node_t *right;
	int value;
    int min;
    int max;
    int gap;
} node_t;

int
fix(int a, int b, int d)
{
	int dd = a > b ? a - b : b - a;
	return dd >= d ? 0 : d - dd;
}

void 
update_gap(node_t *x) 
{
    if (x == NULL) {
        return;
    }
    
    x->min = x->value;
    x->max = x->value;
    x->gap = 0;
    
    if (x->left != NULL) {
        x->min = x->left->min;
        if (x->left->gap > x->gap) {
            x->gap = x->left->gap;
        }
        int d = x->value - x->left->max;
        if (d > x->gap) {
            x->gap = d;
        }
    }
    
    if (x->right != NULL) {
        x->max = x->right->max;
        if (x->right->gap > x->gap) {
            x->gap = x->right->gap;
        }
        int d = x->right->min - x->value;
        if (d > x->gap) {
            x->gap = d;
        }
    }
}

node_t* 
node_insert(node_t *head, int value)
{
	if (head == NULL) {
		node_t *x = malloc(sizeof(node_t));
		x->left = NULL;
		x->right = NULL;
		x->value = value;
        update_gap(x);
		return x;
    }
	
	if (value > head->value) {
		node_t *x = node_insert(head->right, value);
		head->right = x;
    } else if (value < head->value) {
		node_t *x = node_insert(head->left, value);
		head->left = x;
    }

    update_gap(head);
	return head;
}

void
node_free(node_t *x)
{
	if (x != NULL) {
		node_free(x->left);
		node_free(x->right);
		free(x);
    }
}
		

node_t*
node_remove_greater_eq(node_t *x, int value)
{
	if (x == NULL) {
		return NULL;
    }
	
	if (x->value >= value) {
		node_free(x->right);
		node_t *y = node_remove_greater_eq(x->left, value);
		free(x);
		return y;
    } else {
		node_t *y = node_remove_greater_eq(x->right, value);
		x->right = y;
        update_gap(x);
		return x;
	}
}	

node_t*
node_remove_lesser_eq(node_t *x, int value)
{
	if (x == NULL) {
		return NULL;
    }
	
	if (x->value <= value) {
		node_free(x->left);
		node_t *y = node_remove_lesser_eq(x->right, value);
		free(x);
		return y;
    } else {
		node_t *y = node_remove_lesser_eq(x->left, value);
		x->left = y;
        update_gap(x);
		return x;
    }
}
	

int*
airports(int d, int n, int *x)
{
	int *rv = malloc(n * sizeof(int));
	
	rv[0] = 0;
	if (n == 1) {
		return rv;
    }
	
	int low = x[0] < x[1] ? x[0] : x[1];
	int hi = x[0] < x[1] ? x[1] : x[0];
	rv[1] = fix(x[0], x[1], d);
	if (n == 2) {
		return rv;
	}
	
	int mid_low = hi - d;
	int mid_hi = low + d;
	node_t *mid = NULL;
	
	for (int i = 2; i < n; i++) {
		int t = x[i];
		
		if (t > hi) {
			int temp = t;
			t = hi;
			hi = temp;
			mid_low = hi - d;
			mid = node_remove_lesser_eq(mid, mid_low);
		} else if (t < low) {
			int temp = t;
			t = low;
			low = temp;
			mid_hi = low + d;
			mid = node_remove_greater_eq(mid, mid_hi);
		}
		
		if (t > mid_low && t < mid_hi) {
			mid = node_insert(mid, t);
		}
	
		if (mid == NULL) {
			rv[i] = 0;
			continue;
		}
		
		int v1 = 2 * d - (hi - low) - mid->gap;
		int v2 = fix(low, mid->min, d);
		int v3 = fix(hi, mid->max, d);
		
		rv[i] = v1;
		if (v2 < rv[i]) {
			rv[i] = v2;
		}
		if (v3 < rv[i]) {
			rv[i] = v3;
		}
	}
    node_free(mid);
	return rv;
}	

int main() {
    int q; 
    scanf("%i", &q);
    for(int a0 = 0; a0 < q; a0++){
        int n; 
        int d; 
        scanf("%i %i", &n, &d);
        int *x = malloc(sizeof(int) * n);
        for (int x_i = 0; x_i < n; x_i++) {
           scanf("%i",&x[x_i]);
        }
        int result_size;
        int* result = airports(d, n, x);
        for(int result_i = 0; result_i < n; result_i++) {
            if(result_i) {
                printf(" ");
            }
            printf("%d", result[result_i]);
        }
        puts("");


    }
    return 0;
}

 

Warmup
Implementation
Strings
Sorting
Search
Graph Theory
Greedy
Dynamic Programming
Constructive Algorithms
Bit Manipulation
Recursion
Game Theory
NP Complete
Debugging

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionBike Racers – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTime Conversion – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionNo Prefix Set – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionProblem solving – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionHuarongdao – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTicket – HackerRank Solution
Tags: AirportsCc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
29

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Definite Random Walks - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Cutting Boards - HackerRank Solution

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionBike Racers – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTime Conversion – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionNo Prefix Set – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionProblem solving – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionHuarongdao – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTicket – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
Omniscient Reader’s Viewpoint Chapter 122
Anime

Omniscient Readers Viewpoint Chapter 122 Raw Scan English Spoilers

August 30, 2022
42
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Lily’s Homework – HackerRank Solution

May 31, 2022
19
Leetcode All Problems Solutions
Code Solutions

Reverse Pairs – LeetCode Solution

September 10, 2022
73
Leetcode All Problems Solutions
Code Solutions

Super Ugly Number – LeetCode Solution

September 6, 2022
43

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?