Create a method that takes a list of Contact records and inserts only those that have both a FirstName, LastName, and valid AccountId. Return the number of successfully inserted contacts using Database.insert with allOrNone set to false to allow partial success.

Examples:

Input: contacts = [Contact(FirstName='John', LastName='Doe', AccountId='001xxx'), Contact(FirstName='Jane', LastName='Smith', AccountId='001yyy'), Contact(FirstName='Bob', LastName='Wilson', AccountId='001zzz')]
Output: 3
Explanation: All three contacts have FirstName, LastName, and AccountId, so all are inserted

Input: contacts = [Contact(FirstName='John', LastName='Doe', AccountId='001xxx'), Contact(FirstName=null, LastName='Smith', AccountId='001yyy'), Contact(FirstName='Bob', LastName=null, AccountId='001zzz')]
Output: 1
Explanation: Only the first contact has all required fields, so only 1 is successfully inserted

Input: contacts = null
Output: 0
Explanation: Null input returns 0

Apex Code Editor

Welcome to Lightning Challenge!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay May 2026

Contest runs May 1 - 31. Complete challenges to climb the leaderboard!

Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In