Amazon Interview Question for Software Engineers


Country: United States




Comment hidden because of low score. Click to expand.
0
of 0 vote

@Silvimasss, checking whether they are digits is not enough since ip addresses always fall between ranges 0 - 255. So, you have to check that as well.

Elegant solution in Python:

def isValidIP(ip):
    parts = ip.split('.')
    if len(parts) != 4:
        return False
    if any(part.isalpha() for part in parts):
        return False
    return all(0 <= int(part) <= 255 for part in parts)

Test code:

valid, invalid = [], []
ip_addresses = ["192.100.0.1", "10.0.0.1", "aa.bb.cc.dd", "10.0", "999.10.10.1"]
for ip_addr in ip_addresses:
     valid.append(ip_addr) if isValidIP(ip_addr) else invalid.append(ip_addr)

print 'Valid IPs = ', valid
print 'Invalid IPs = ', invalid
'''
OUTPUT:
Valid IPs =  ['192.100.0.1', '10.0.0.1']
Invalid IPs =  ['aa.bb.cc.dd', '10.0', '999.10.10.1']
'''

- prudent_programmer March 29, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class IPv4:
    def __init__(self, ips):
        self.ip_list = ips

    def validate(self):
        ip_list = self.ip_list
        if(len(ip_list)):
            for ip in ip_list:
                if(not len(ip)):
                    print("Empty IP provided")
                    continue

                if(bool(re.match('[\d.]+$',ip))) :
                    token = ip.split(".")
                    if(len(token) and len(token) == 4):
                        isValid = True
                        for t in token:
                            if t.isdigit() and int(t) >=0 and int(t) <=255:
                                continue
                            else:
                                print("Invalid token %s"%ip)
                                isValid = False
                                break
                        if isValid:
                            print("valid IP %s" %ip)
                    else:
                        print ("Too few subnets in %s"%ip)
                else:
                    print("%s has characters not allowed"%(ip))
        else:
            print("IP Address list is empty");

ip = IPv4(["10.5.6.4", "10", "", "a.b.c.d", "256,0,254.1", "1,2,3.4", "1.2.3.4"])
ip.validate()

- vikalpveer March 30, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
This will also check the range of the IP address i.e <= 255
*/
public class ValidateIPAddress {
	public static void main(String[] args) {
		String ipAddresses[] = {"192.168.1.100", "1092.1688.1.100", "12.ab.c.235", "abv.cdd.cd.a", "192.168.1.45e"};
		String patternString = "\\d+.\\d+.\\d+.\\d+";
		StringBuffer valid = new StringBuffer();
		StringBuffer invalid = new StringBuffer();
		for(int i = 0; i < ipAddresses.length; i++) {
			if(isValid(ipAddresses[i], patternString)) {
				valid.append(ipAddresses[i]+"\n");
			}else {
				invalid.append(ipAddresses[i]+"\n");
			}
		}
		System.out.println("Valid ip address:\n"+valid.toString());
		System.out.println("InValid ip address:\n"+invalid.toString());
	}

	private static boolean isValid(String string, String patternString) {
		String array[] = string.split("\\.");
		if(array.length != 4) {
			return false;
		}else {
			for(int i = 0; i < array.length; i++) {
				if(array[i].matches(".*[a-zA-Z].*") || !(Integer.parseInt(array[i]) <= 255)) {
					return false;
				}
			}
		}
		Pattern pattern = Pattern.compile(patternString);
		Matcher matcher = pattern.matcher(string);
		boolean b = matcher.matches();
		return b;
		
	}
}
/*
 * 
Valid ip address:
192.168.1.100

InValid ip address:
1092.1688.1.100
12.ab.c.235
abv.cdd.cd.a
192.168.1.45e
 * */

- Bushan SC April 05, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function isValidIP(ip) {
  ip = ip.split(".");
  if(ip.length !== 4)
    return false;
  for(var j=0;j<ip.length;j++) {
    if(isNaN(ip[j]) || ip[j] < 0 || ip[j] > 255)
      return false;
  }
  return true;
}
function ips() {
  var ipAddr = ["192.100.0.1", "10.0.0.1", "aa.bb.cc.dd", "10.0", "999.10.10.1"]; 
  var valid = [];
  var invalid = [];
  for(var i=0;i<ipAddr.length;i++) {
   if(isValidIP(ipAddr[i])) {
     valid.push(ipAddr[i]);
   }
    else {
      invalid.push(ipAddr[i]);
    }
  }
  console.log("Valid IPs : " + valid);
  console.log("Invalid IPs : " + invalid);
}  
ips()

- Gaurav July 22, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IP {
    public static void main(String[] args){
        String[] arr = {"192.100.0.0","192.100.111.111", "10.0.0.1","a.b.c.d", "10.0", "999.10.10.1"};
        String patternString = "\\d+.\\d+.\\d+.\\d+";
        StringBuffer valid1 = new StringBuffer();
        StringBuffer invalid1 = new StringBuffer();
        for(int i=0;i<arr.length;i++) {
            
            if(validIP((arr[i]),patternString)) {
                valid1.append(arr[i]);
            }else{
                invalid1.append(arr[i]);
            }
        }
        System.out.println("valid --> " + valid1.toString());
        System.out.println("invalid --> "+ invalid1.toString());
    }
    public static boolean validIP(String s, String patternString){
        Pattern p = Pattern.compile(patternString);
        Matcher m = p.matcher(s);
        boolean  b = m.matches();
    return b;
    }
}

Please add the reason for down sizing my code.

- silvimasss March 29, 2018 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More