Skip to content

Instantly share code, notes, and snippets.

@patelrohan
Created November 10, 2017 07:56
Show Gist options
  • Save patelrohan/7c6ed3827d451f905dce37b6daea41b8 to your computer and use it in GitHub Desktop.
Save patelrohan/7c6ed3827d451f905dce37b6daea41b8 to your computer and use it in GitHub Desktop.
Find first unique integer from an array
//
// main.m
// Algorithm
//
// Created by Rohan Patel on 11/10/17.
// Copyright © 2017 Rohan Patel. All rights reserved.
//
/*
Note: I found two mistakes in the proposed solution during the interview:
* i) Mutable dictionary is required to be able to add elements instead of immutable dictionary.
* ii) NSMutableDictionary/ NSDictionary does not guarantee the order of the key-value pairs. Subclassing it might be an option to achieve the ordered Dictionary list.
*/
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
//NSLog(@"Hello, World!");
NSArray *array = @[@1,@2,@3,@2,@1, @3, @7, @6];
//NSArray *array = @[@1,@2,@3,@2,@1, @3, @7, @6, @7, @6];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
/* First for loop to scan the integer elements and insert them into Dictionary as key-value pairs.
* Key = integer of an array
* Value = Counter for occurance of particular integer
*/
for (int i=0; i < [array count]; i++) {
if ([dict objectForKey:array[i]]){
long int count = [[dict objectForKey:array[i]]integerValue];
[dict setObject:[NSNumber numberWithInt:++count] forKey:array[i]];
}
else{
[dict setObject:[NSNumber numberWithInt:1] forKey:array[i]];
}
}
NSLog(@"%@",dict);
/* Second for loop to scan the Dictionary to look for the first unique element
*/
BOOL isUniqueCharFound = NO;
for (id key in dict) {
long int value = [[dict objectForKey: key]integerValue];
if (value == 1) {
NSLog(@"--> %ld", [key integerValue]);
isUniqueCharFound = YES;
break;
}
}
if (!isUniqueCharFound) {
NSLog(@"There is not any unique integer in the array!");
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment