Tuesday, 21 March 2023

Most popular coding interview question on LinkedList

 Introduction:

Welcome to this blog where we will discuss the popular coding interview question on LinkedList. LinkedList is one of the most common data structures used in programming, and its implementation can be found in almost every programming language. In this blog, we will go through a common LinkedList question and its answer that can help you prepare for your next coding interview.


Question:

Given a LinkedList, write a function to reverse it.


Solution:

To reverse a LinkedList, we need to reverse the direction of all the pointers. We can do this by iterating through the list and updating the pointers to point in the opposite direction. Here is the step-by-step approach to reverse a LinkedList:


Create three pointer variables: previous, current, and next. The previous pointer will initially be null, and the current pointer will point to the head of the LinkedList.


Traverse through the LinkedList, updating the next pointer to the current node's next node and then updating the current node's next pointer to the previous node.


Move the previous pointer to the current node and move the current node to the next node.


Repeat steps 2 and 3 until the end of the LinkedList is reached.


Set the head pointer of the LinkedList to the previous pointer.


Here is the implementation of the above approach:



class LinkedListNode {

  constructor(value) {

    this.value = value;

    this.next = null;

  }

}


function reverseLinkedList(head) {

  let previous = null;

  let current = head;

  let next = null;


  while (current != null) {

    next = current.next;

    current.next = previous;

    previous = current;

    current = next;

  }


  return previous;

}

In the above implementation, we first initialize the three pointers to null or the head of the LinkedList. Then we traverse through the LinkedList and update the pointers' values. Finally, we set the head pointer of the LinkedList to the previous pointer, which will be the last node of the original LinkedList.


Conclusion:

In this blog, we have discussed a common LinkedList question and its solution. Reversing a LinkedList is a popular question asked in coding interviews, and its implementation can be found in almost every programming language. By understanding the above approach, you can easily solve this problem and ace your coding interview.

Sunday, 12 March 2023

Experience Interview Question and Answer on Java Stream API

 Introduction:

Java Stream API is a powerful feature introduced in Java 8 that provides a functional programming style for processing collections of data. In this article, we will discuss some experience interview questions related to Java Stream API and provide answers to help you prepare for your next interview.


Question 1: What is the difference between a Stream and a Collection in Java?

Answer: A Collection is a data structure that holds a group of objects, whereas a Stream is a sequence of objects that can be processed in a functional style. Collections are typically used for storing and retrieving data, while Streams are used for processing and transforming data.


Question 2: What are the benefits of using Java Stream API?

Answer: Java Stream API provides several benefits, including:


Simplifies processing of large data sets

Enables parallel processing for improved performance

Provides a functional programming style for more concise and expressive code

Supports lazy evaluation, which reduces memory usage and improves performance

Question 3: What is the difference between intermediate and terminal operations in Java Stream API?

Answer: Intermediate operations are operations that transform a Stream into another Stream, while terminal operations are operations that produce a result or a side-effect. Intermediate operations include operations like filter(), map(), and sorted(), while terminal operations include operations like forEach(), collect(), and reduce().


Question 4: How do you convert a Stream to a List in Java?

Answer: To convert a Stream to a List in Java, you can use the collect() method with the Collectors.toList() method, as shown below:


List<String> list = stream.collect(Collectors.toList());


Question 5: What is lazy evaluation in Java Stream API?

Answer: Lazy evaluation is a technique used in Java Stream API that postpones the evaluation of an operation until it is actually needed. This allows for more efficient use of memory and can improve performance. Lazy evaluation is supported by intermediate operations in Stream API.


Conclusion:

Java Stream API is a powerful feature that provides a functional programming style for processing collections of data. In this article, we discussed some experience interview questions related to Java Stream API and provided answers to help you prepare for your next interview. By understanding these concepts and practicing with Java Stream API.

Understanding Functional Interfaces in Java 8 with Examples

 Introduction:

Functional interfaces are a key feature of Java 8. They enable the use of lambda expressions and method references, which are essential for functional programming in Java. In this article, we will explore what functional interfaces are and how they work in Java 8.


What is a Functional Interface?

A functional interface is an interface that has only one abstract method. An abstract method is a method that does not have an implementation. Functional interfaces are also known as SAM (Single Abstract Method) interfaces.


Functional interfaces are used to represent lambda expressions and method references. They provide a way to define the signature of a lambda expression or a method reference.


Examples of Functional Interfaces:

Java 8 provides several built-in functional interfaces that can be used for different purposes. Here are some examples of built-in functional interfaces in Java 8:


Predicate

The Predicate interface represents a function that takes an argument and returns a boolean value. It is commonly used for filtering elements in a collection.

Here is an example of using a Predicate to filter a list of integers:


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

Predicate<Integer> evenPredicate = n -> n % 2 == 0;

List<Integer> evenNumbers = numbers.stream()

.filter(evenPredicate)

.collect(Collectors.toList());


In this code, we define a Predicate that checks if an integer is even. We then use the filter() method to filter out the odd integers from the list.


Consumer

The Consumer interface represents a function that takes an argument and returns no result. It is commonly used for iterating over a collection and performing some action on each element.

Here is an example of using a Consumer to print the elements of a list:


List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

Consumer<String> printConsumer = System.out::println;

names.forEach(printConsumer);


In this code, we define a Consumer that prints a string to the console. We then use the forEach() method to iterate over the list and apply the Consumer to each element.


Function

The Function interface represents a function that takes an argument and returns a result. It is commonly used for transforming elements in a collection.

Here is an example of using a Function to convert a list of strings to a list of integers:


List<String> stringNumbers = Arrays.asList("1", "2", "3", "4", "5");

Function<String, Integer> parseIntFunction = Integer::parseInt;

List<Integer> numbers = stringNumbers.stream()

.map(parseIntFunction)

.collect(Collectors.toList());


In this code, we define a Function that converts a string to an integer. We then use the map() method to apply the Function to each element in the list and convert it to an integer.


Conclusion:

Functional interfaces are a powerful feature of Java 8 that enable functional programming in Java. They provide a way to represent lambda expressions and method references, and make it easier to write concise and expressive code. In this article, we explored what functional interfaces are and how they work in Java 8, with examples of built-in functional interfaces in Java 8.

Exploring the New Features in Java 8

 Introduction:

Java 8, released in 2014, introduced several new features and improvements to the Java programming language. In this article, we will explore some of the major features of Java 8.


Lambda Expressions:

Lambda expressions are one of the most significant features of Java 8. They enable functional programming style in Java by providing a concise way of representing anonymous functions. Lambda expressions are essentially a way to pass behavior as a method argument.


For example, consider the following code snippet that uses a lambda expression to sort a list of integers:


List<Integer> numbers = Arrays.asList(5, 2, 7, 1, 9);

Collections.sort(numbers, (a, b) -> a.compareTo(b));


Here, we pass a lambda expression as the second argument to the sort() method, which compares two integers and returns the result.


Stream API:

The Stream API is another major feature of Java 8. It allows you to process collections of objects in a functional way. The Stream API provides a set of operations like filter, map, reduce, and more. These operations can be used to transform, filter, and aggregate data in a declarative way.


For example, consider the following code snippet that uses the Stream API to filter and map a list of strings:


List<String> words = Arrays.asList("hello", "world", "java");

List<String> filteredWords = words.stream()

.filter(s -> s.startsWith("j"))

.map(String::toUpperCase)

.collect(Collectors.toList());


In this code, we use the filter() method to filter out the strings that do not start with the letter 'j', then use the map() method to convert the filtered strings to upper case, and finally use the collect() method to collect the results into a new list.


Date and Time API:

Java 8 introduced a new Date and Time API that provides a more comprehensive and flexible way of handling dates and times. The new API provides classes like LocalDate, LocalTime, LocalDateTime, and more, which are immutable and thread-safe.


For example, consider the following code snippet that uses the new Date and Time API to create a date and time object:


LocalDateTime now = LocalDateTime.now();


This code creates a new LocalDateTime object that represents the current date and time.


Optional Class:

The Optional class is another useful feature introduced in Java 8. It provides a more elegant way of handling null values. The Optional class is essentially a container object that may or may not contain a non-null value.


For example, consider the following code snippet that uses the Optional class to avoid null pointer exceptions:


String name = getName();

Optional<String> optionalName = Optional.ofNullable(name);

String defaultName = "John Doe";

String finalName = optionalName.orElse(defaultName);


In this code, we use the ofNullable() method to create an Optional object that may or may not contain a non-null value. We then use the orElse() method to provide a default value in case the Optional object is empty.


Conclusion:

Java 8 introduced several new features and improvements that make Java programming more expressive, concise, and flexible. In this article, we explored some of the major features of Java 8, including lambda expressions, the Stream API, the Date and Time API, the Optional class, and more. These features have made Java a more powerful and modern programming language

Saturday, 4 March 2023

How Does Java Memory Work: Understanding the Basics

 Introduction:


Hello, Java developers! If you're reading this post, chances are you're curious about how Java manages memory. Memory management is a crucial aspect of any programming language, as it affects the performance, stability, and security of software applications. In Java, memory management is handled automatically by the Java Virtual Machine (JVM), which uses a combination of techniques to allocate, use, and release memory. In this post, we'll explore how Java memory works and what you need to know to optimize your code.


Section 1: Java Memory Model


The first thing to understand about Java memory is the Java Memory Model (JMM), which defines the rules and semantics of how threads access and modify memory. In Java, memory is divided into two main areas: the heap and the stack. The heap is a shared memory area that stores objects and arrays, while the stack is a private memory area that stores local variables and method calls. The JVM also uses other memory areas, such as the method area and the native heap, for storing classes and native code.


Section 2: Garbage Collection


The second thing to understand about Java memory is Garbage Collection (GC), which is the process of reclaiming memory that is no longer used by objects. In Java, GC is automatic and transparent to the programmer. The JVM periodically scans the heap to identify objects that are no longer reachable from the application code, and releases their memory. GC uses different algorithms and strategies, such as Mark and Sweep, Copying, and Generational, to optimize the collection process and minimize the impact on the application's performance.


Section 3: Memory Optimization Techniques


The third thing to understand about Java memory is how to optimize it for your application. Java provides several techniques for controlling and monitoring memory usage, such as:


Memory allocation: You can control how much memory your application uses by setting the initial and maximum heap sizes using command-line options or environment variables. You can also use the -Xmx and -Xms flags to specify the minimum and maximum heap sizes.


Object pooling: You can reuse objects instead of creating new ones, to reduce memory fragmentation and GC overhead. Object pooling can be done manually or using third-party libraries, such as Apache Commons Pool or Netflix Hystrix.


Memory profiling: You can monitor the memory usage of your application using memory profiling tools, such as jvisualvm or YourKit. Memory profiling can help you identify memory leaks, excessive object creation, and inefficient algorithms.


Conclusion:


That's it for this post on how Java memory works. By understanding the basics of Java Memory Model, Garbage Collection, and memory optimization techniques, you can write more efficient and scalable Java code. Remember to test your code in different scenarios and monitor its performance using profiling tools. Happy coding!

How to Prepare for a Java Developer Interview: Your Ultimate Guide

 Introduction:


Hello, aspiring Java developers! If you're reading this post, chances are you're preparing for a job interview in the field of Java development. Congratulations! Java is a popular and versatile programming language that is widely used in various industries, such as finance, healthcare, and e-commerce. However, landing a Java developer job requires more than just knowing the syntax and libraries. You also need to demonstrate your skills, experience, and attitude to potential employers. That's where this guide comes in. In this post, we'll share some tips and strategies on how to prepare for a Java developer interview.


Section 1: Know the Basics


The first step in preparing for a Java developer interview is to know the basics of the language and its ecosystem. This includes:


Core concepts: Make sure you understand the fundamental concepts of Java, such as objects, classes, inheritance, polymorphism, and interfaces. Review the syntax and semantics of the language, and practice writing simple programs that demonstrate your knowledge.


Libraries and frameworks: Familiarize yourself with the most popular libraries and frameworks in the Java ecosystem, such as Spring, Hibernate, Maven, and JUnit. Understand their purpose, features, and best practices, and be prepared to explain how you would use them in a project.


Tools and IDEs: Learn how to use the common tools and IDEs for Java development, such as Eclipse, IntelliJ, Git, and Jenkins. Practice setting up a development environment, debugging code, and collaborating with other developers using version control.


Section 2: Practice Coding Exercises


The second step in preparing for a Java developer interview is to practice coding exercises that simulate real-world scenarios. This includes:


Data structures and algorithms: Practice implementing and using data structures and algorithms, such as arrays, linked lists, stacks, queues, trees, graphs, sorting, searching, and dynamic programming. Understand the time and space complexity of each algorithm, and be able to optimize them when necessary.


Design patterns and principles: Practice applying the design patterns and principles of Java, such as SOLID, MVC, Observer, and Factory. Understand the pros and cons of each pattern, and be able to explain how they improve the quality and maintainability of code.


Problem-solving and creativity: Practice solving coding challenges that require creativity and problem-solving skills, such as building a web application, a game, or a machine learning model. Be able to explain your thought process, trade-offs, and solutions.


Section 3: Prepare for Behavioral Questions


The third step in preparing for a Java developer interview is to prepare for behavioral questions that assess your personality, communication skills, and teamwork. This includes:


Motivation and passion: Be prepared to explain why you chose Java development as a career, and what motivates you to learn and improve your skills. Show your enthusiasm for the field and your willingness to take on new challenges.


Experience and achievements: Be prepared to give examples of your past experiences and achievements in Java development, such as projects you have worked on, problems you have solved, or skills you have acquired. Highlight your strengths and how they can contribute to the company.


Communication and teamwork: Be prepared to demonstrate your communication and teamwork skills, such as how you collaborate with others, how you handle conflicts, and how you give and receive feedback. Show your ability to work in a team and your willingness to learn from others.


Conclusion:


That's it for this ultimate guide on how to prepare for a Java developer interview. By following these tips and strategies, you can increase your chances of landing your dream job and advancing your career in Java development. Remember to

Sunday, 11 August 2019

91 job interview questions for data scientists

  1. What is the biggest data set that you processed, and how did you process it, what were the results?
  2. Tell me two success stories about your analytic or computer science projects? How was lift (or success) measured?
  3. What is: lift, KPI, robustness, model fitting, design of experiments, 80/20 rule?
  4. What is: collaborative filtering, n-grams, map reduce, cosine distance?
  5. How to optimize a web crawler to run much faster, extract better information, and better summarize data to produce cleaner databases?
  6. How would you come up with a solution to identify plagiarism?
  7. How to detect individual paid accounts shared by multiple users?
  8. Should click data be handled in real time? Why? In which contexts?
  9. What is better: good data or good models? And how do you define "good"? Is there a universal good model? Are there any models that are definitely not so good?
  10. What is probabilistic merging (AKA fuzzy merging)? Is it easier to handle with SQL or other languages? Which languages would you choose for semi-structured text data reconciliation? 
  11. How do you handle missing data? What imputation techniques do you recommend?
  12. What is your favorite programming language / vendor? why?
  13. Tell me 3 things positive and 3 things negative about your favorite statistical software.
  14. Compare SAS, R, Python, Perl
  15. What is the curse of big data?
  16. Have you been involved in database design and data modeling?
  17. Have you been involved in dashboard creation and metric selection? What do you think about Birt?
  18. What features of Teradata do you like?
  19. You are about to send one million email (marketing campaign). How do you optimze delivery? How do you optimize response? Can you optimize both separately? (answer: not really)
  20. Toad or Brio or any other similar clients are quite inefficient to query Oracle databases. Why? How would you do to increase speed by a factor 10, and be able to handle far bigger outputs? 
  21. How would you turn unstructured data into structured data? Is it really necessary? Is it OK to store data as flat text files rather than in an SQL-powered RDBMS?
  22. What are hash table collisions? How is it avoided? How frequently does it happen?
  23. How to make sure a mapreduce application has good load balance? What is load balance?
  24. Examples where mapreduce does not work? Examples where it works very well? What are the security issues involved with the cloud? What do you think of EMC's solution offering an hybrid approach - both internal and external cloud - to mitigate the risks and offer other advantages (which ones)?
  25. Is it better to have 100 small hash tables or one big hash table, in memory, in terms of access speed (assuming both fit within RAM)? What do you think about in-database analytics?
  26. Why is naive Bayes so bad? How would you improve a spam detection algorithm that uses naive Bayes?
  27. Have you been working with white lists? Positive rules? (In the context of fraud or spam detection)
  28. What is star schema? Lookup tables? 
  29. Can you perform logistic regression with Excel? (yes) How? (use linest on log-transformed data)? Would the result be good? (Excel has numerical issues, but it's very interactive)
  30. Have you optimized code or algorithms for speed: in SQL, Perl, C++, Python etc. How, and by how much?
  31. Is it better to spend 5 days developing a 90% accurate solution, or 10 days for 100% accuracy? Depends on the context?
  32. Define: quality assurance, six sigma, design of experiments. Give examples of good and bad designs of experiments.
  33. What are the drawbacks of general linear model? Are you familiar with alternatives (Lasso, ridge regression, boosted trees)?
  34. Do you think 50 small decision trees are better than a large one? Why?
  35. Is actuarial science not a branch of statistics (survival analysis)? If not, how so?
  36. Give examples of data that does not have a Gaussian distribution, nor log-normal. Give examples of data that has a very chaotic distribution?
  37. Why is mean square error a bad measure of model performance? What would you suggest instead?
  38. How can you prove that one improvement you've brought to an algorithm is really an improvement over not doing anything? Are you familiar with A/B testing?
  39. What is sensitivity analysis? Is it better to have low sensitivity (that is, great robustness) and low predictive power, or the other way around? How to perform good cross-validation? What do you think about the idea of injecting noise in your data set to test the sensitivity of your models?
  40. Compare logistic regression w. decision trees, neural networks. How have these technologies been vastly improved over the last 15 years?
  41. Do you know / used data reduction techniques other than PCA? What do you think of step-wise regression? What kind of step-wise techniques are you familiar with? When is full data better than reduced data or sample?
  42. How would you build non parametric confidence intervals, e.g. for scores? (see the AnalyticBridge theorem)
  43. Are you familiar either with extreme value theory, monte carlo simulations or mathematical statistics (or anything else) to correctly estimate the chance of a very rare event?
  44. What is root cause analysis? How to identify a cause vs. a correlation? Give examples.
  45. How would you define and measure the predictive power of a metric?
  46. How to detect the best rule set for a fraud detection scoring technology? How do you deal with rule redundancy, rule discovery, and the combinatorial nature of the problem (for finding optimum rule set - the one with best predictive power)? Can an approximate solution to the rule set problem be OK? How would you find an OK approximate solution? How would you decide it is good enough and stop looking for a better one?
  47. How to create a keyword taxonomy?
  48. What is a Botnet? How can it be detected?
  49. Any experience with using API's? Programming API's? Google or Amazon API's? AaaS (Analytics as a service)?
  50. When is it better to write your own code than using a data science software package?
  51. Which tools do you use for visualization? What do you think of Tableau? R? SAS? (for graphs). How to efficiently represent 5 dimension in a chart (or in a video)?
  52. What is POC (proof of concept)?
  53. What types of clients have you been working with: internal, external, sales / finance / marketing / IT people? Consulting experience? Dealing with vendors, including vendor selection and testing?
  54. Are you familiar with software life cycle? With IT project life cycle - from gathering requests to maintenance? 
  55. What is a cron job? 
  56. Are you a lone coder? A production guy (developer)? Or a designer (architect)?
  57. Is it better to have too many false positives, or too many false negatives?
  58. Are you familiar with pricing optimization, price elasticity, inventory management, competitive intelligence? Give examples. 
  59. How does Zillow's algorithm work? (to estimate the value of any home in US)
  60. How to detect bogus reviews, or bogus Facebook accounts used for bad purposes?
  61. How would you create a new anonymous digital currency?
  62. Have you ever thought about creating a startup? Around which idea / concept?
  63. Do you think that typed login / password will disappear? How could they be replaced?
  64. Have you used time series models? Cross-correlations with time lags? Correlograms? Spectral analysis? Signal processing and filtering techniques? In which context?
  65. Which data scientists do you admire most? which startups?
  66. How did you become interested in data science?
  67. What is an efficiency curve? What are its drawbacks, and how can they be overcome?
  68. What is a recommendation engine? How does it work?
  69. What is an exact test? How and when can simulations help us when we do not use an exact test?
  70. What do you think makes a good data scientist?
  71. Do you think data science is an art or a science?
  72. What is the computational complexity of a good, fast clustering algorithm? What is a good clustering algorithm? How do you determine the number of clusters? How would you perform clustering on one million unique keywords, assuming you have 10 million data points - each one consisting of two keywords, and a metric measuring how similar these two keywords are? How would you create this 10 million data points table in the first place?
  73. Give a few examples of "best practices" in data science.
  74. What could make a chart misleading, difficult to read or interpret? What features should a useful chart have?
  75. Do you know a few "rules of thumb" used in statistical or computer science? Or in business analytics?
  76. What are your top 5 predictions for the next 20 years?
  77. How do you immediately know when statistics published in an article (e.g. newspaper) are either wrong or presented to support the author's point of view, rather than correct, comprehensive factual information on a specific subject? For instance, what do you think about the official monthly unemployment statistics regularly discussed in the press? What could make them more accurate?
  78. Testing your analytic intuition: look at these three charts. Two of them exhibit patterns. Which ones? Do you know that these charts are called scatter-plots? Are there other ways to visually represent this type of data?
  79. You design a robust non-parametric statistic (metric) to replace correlation or R square, that (1) is independent of sample size, (2) always between -1 and +1, and (3) based on rank statistics. How do you normalize for sample size? Write an algorithm that computes all permutations of n elements. How do you sample permutations (that is, generate tons of random permutations) when n is large, to estimate the asymptotic distribution for your newly created metric? You may use this asymptotic distribution for normalizing your metric. Do you think that an exact theoretical distribution might exist, and therefore, we should find it, and use it rather than wasting our time trying to estimate the asymptotic distribution using simulations? 
  80. More difficult, technical question related to previous one. There is an obvious one-to-one correspondence between permutations of n elements and integers between 1 and n! Design an algorithm that encodes an integer less than n! as a permutation of n elements. What would be the reverse algorithm, used to decode a permutation and transform it back into a number? Hint: An intermediate step is to use the factorial number system representation of an integer. Feel free to check this reference online to answer the question. Even better, feel free to browse the web to find the full answer to the question (this will test the candidate's ability to quickly search online and find a solution to a problem without spending hours reinventing the wheel).  
  81. How many "useful" votes will a Yelp review receive? My answer: Eliminate bogus accounts (read this article), or competitor reviews (how to detect them: use taxonomy to classify users, and location - two Italian restaurants in same Zip code could badmouth each other and write great comments for themselves). Detect fake likes: some companies (e.g. FanMeNow.com) will charge you to produce fake accounts and fake likes. Eliminate prolific users who like everything, those who hate everything. Have a blacklist of keywords to filter fake reviews. See if IP address or IP block of reviewer is in a blacklist such as "Stop Forum Spam". Create honeypot to catch fraudsters.  Also watch out for disgruntled employees badmouthing their former employer. Watch out for 2 or 3 similar comments posted the same day by 3 users regarding a company that receives very few reviews. Is it a brand new company? Add more weight to trusted users (create a category of trusted users).  Flag all reviews that are identical (or nearly identical) and come from same IP address or same user. Create a metric to measure distance between two pieces of text (reviews). Create a review or reviewer taxonomy. Use hidden decision trees to rate or score review and reviewers.
  82. What did you do today? Or what did you do this week / last week?
  83. What/when is the latest data mining book / article you read? What/when is the latest data mining conference / webinar / class / workshop / training you attended? What/when is the most recent programming skill that you acquired?
  84. What are your favorite data science websites? Who do you admire most in the data science community, and why? Which company do you admire most?
  85. What/when/where is the last data science blog post you wrote? 
  86. In your opinion, what is data science? Machine learning? Data mining?
  87. Who are the best people you recruited and where are they today?
  88. Can you estimate and forecast sales for any book, based on Amazon public data? Hint: read this article.
  89. What's wrong with this picture?
  90. Should removing stop words be Step 1 rather than Step 3, in the search engine algorithm described here? Answer: Have you thought about the fact that mine and yours could also be stop words? So in a bad implementation, data mining would become data mine after stemming, then data. In practice, you remove stop words before stemming. So Step 3 should indeed become step 1. 
  91. Experimental design and a bit of computer science with Lego's